これが私が持っているコードです。それは問題なくコンパイルされ、何が問題なのかわかりません。
// 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 つの係数を入力する段階に到達します。return がプッシュされるとすぐにエラーが発生します。