这是我得到的代码。编译得很好,我根本看不出可能出错的地方:
// This program takes a quadratic from the user, and prints the solution(s) if they exist.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
//Make sign function for switch test - because in the switch expression itself, C refused to believe x/|x| is an integer...
int sign(float f){
printf("\n\nSIGN CALL OK\n\n");
int sign=f/cabs(f);
return sign;
}
// Define quadratic structure
typedef struct quadratic{
float a, b, c;
float discriminant;
float real_root_1;
float real_root_2;
float complex_root;
} Quadratic;
// 'Redefine' malloc to also check allocation of memory when called.
Quadratic* xmalloc(size_t n){
printf("\n\nXMALLOC CALL OK\n\n");
Quadratic* p = malloc(n);
if (p == NULL) {
printf("\n ERROR: Unable to allocate memory! \n");
exit(1);
}
return p;
}
// newquadratic lets the user define the quadratic to be solved, and returns the pointer to its structure.
Quadratic* newquadratic() {
Quadratic* q = xmalloc(sizeof *q);
printf("\n Please enter the coefficients of the quadratic separated by spaces: ");
scanf("%g, %g, %g", q->a, q->b, q->c);
printf("\n\nDATA ACCEPTED\n\n");
return q;
}
// solve takes the existing data from the quadratics structure and defines the remaining quantities, depending on which
// case we get for the 'sign of the discriminant'.
int solve(Quadratic eqn){
printf("\n\nSOLVE CALL OK\n\n");
eqn.discriminant = (eqn.b*eqn.b - 4*eqn.a*eqn.c);
switch (sign(eqn.discriminant)) {
case -1:
eqn.real_root_1 = (-eqn.b+sqrt(eqn.discriminant))/(2*eqn.a);
eqn.real_root_2 = (-eqn.b-sqrt(eqn.discriminant))/(2*eqn.a);
break;
case 0:
eqn.real_root_1 = (-eqn.b+sqrt(eqn.discriminant))/(2*eqn.a);
break;
case 1:
eqn.complex_root = (-eqn.b+sqrt(eqn.discriminant))/(2*eqn.a);
break;
}
return sign(eqn.discriminant);
}
//main also uses sign of the discriminant (as returned by solve) to decide how to behave appropriately for the case it receives.
int main () {
Quadratic* eqn=newquadratic();
printf("\n\n GET QUADRATIC OK\n\n");
switch (solve(*eqn)) {
case -1:
printf("\n\n We have two real solutions, %g and %g", eqn->real_root_1, eqn->real_root_2);
break;
case 0:
printf("\n\n We have one repeated real solution, %g", eqn->real_root_1);
break;
case 1:
printf("\n\n We have two complex solutions, %g%+gi and %g%-gi", creal(eqn->complex_root),cimag(eqn->complex_root),creal(eqn->complex_root),(-1)*cimag(eqn->complex_root));
break;
}
return 0;
}
xmalloc正确调用,我们进入用户输入3个系数的阶段。一旦返回,我们就会收到错误。
答案 0 :(得分:2)
问题在于你的函数newquadratic。
scanf函数应该给出应该将结果放入其中的变量的地址,同时你实际上传递了变量所持有的值。
要修复,请传递a,b和c的地址,如下所示:(添加&
个字符)
Quadratic* newquadratic()
{
Quadratic* q = xmalloc(sizeof *q);
printf("\n Please enter the coefficients of the quadratic separated by spaces: ");
scanf("%g, %g, %g", &q->a, &q->b, &q->c);
printf("\n\nDATA ACCEPTED\n\n");
return q;
}