I've been racking my brain at this problem since yesterday and I was hoping someone could point me in the right direction. I'm new to C and we must create a program where the user enters a series of linear equations that must be solved with Cramer's rule. The math is not a problem, however I am not sure how to get the coefficients from an entire equation composed of chars and ints.

The user input should look like a series of linear equations such as:

-3x-3y-1z=6

2x+3y+4z=9

3x+2y+4z=10

This would be simple if we were allowed to only enter the coefficients but sadly the whole equation must be entered. You can assume that there are no spaces in the equation, the order of variables will be the same, and that the equations are valid.

I was thinking about storing the whole equation in an array and searching for each variable (x,y,z) then finding the int before the variable, but I cannot determine a way to convert these found variables into integers.

Any help is greatly appreciated. Thanks in advance.

有帮助吗?

解决方案 3

//ax+bx+cz=d, -999 <= a,b,c,d <= 999
int a, b, c, d, i ,j;
char A[5], B[5], C[5], D[5], str[22];
char *pntr;

printf("Enter equation: ");
fgets(str, 21, stdin);

pntr = A;
i = j = 0;
while(1){
    if(str[i] == 'x'){pntr[j] = '\0'; pntr = B; j = 0; i++; continue;}
    else if(str[i] == 'y'){pntr[j] = '\0'; pntr = C; j = 0; i++; continue;}
    else if(str[i] == 'z'){pntr[j] = '\0'; pntr = D; j = 0; i += 2; continue;}
    else if(str[i] == '\n' || str[i] == '\0'){pntr[j] = '\0'; break;}

    pntr[j] = str[i];

    i++;
    j++;
}

a = atoi(A);
b = atoi(B);
c = atoi(C);
d = atoi(D);

printf("%d %d %d %d \n", a, b, c, d);

valter

其他提示

You can split on x/y/z/= with strtok and then use atoi to transform the char* into int.

Read the man strtok and the man atoi for further information (functions from stdlib).

Your idea will work. I once did that on a very similar project at school, it was a nightmare but it (kinda) worked. You'll need some logic to read more than one number, unless you want to restrict yourself to coefficients lower than two digits. If I remember correctly, I started reading the characters until I found a variable in the expression, then I converted and assigned the value I found to that variable for resolving.

To transform your characters into integers you can use the atoi() function, which receives a string of characters and returns the corresponding integer.


If you're willing to invest extra time, and if you're working under *nix, you may want to dig into regular expression's territory with regex.h. You'll minimize your code, but it won't be easy if you haven't worked with regular expressions before.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top