作業雖然寫過了, 反正考試也還是要會...
底下是一種大程式常用的基本結構.
初學的人極有可能會看不下去...
可是真正程式寫大了很容易就長這副德性.
看不下去的, 看 main() 裡頭的 switch-case 就好.
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# define EQT_X_MANY 1
# define EQT_X_NONE 2
# define EQT_X_LINEAR 3
# define EQT_X_QUADRIC 4
# define EQT_X_COMPLEX 5
# define EPSILON 1.0E-6
# define fiszero(x) (fcmp(x, 0.0) == 0)
int getceff(double [3]);
int solve_linear(double t[2], double *x);
int solve_quadric(double t[3], double *x1, double *x2);
int fcmp(double, double);
int main()
{
double t[3], x1, x2;
int type;
getceff(t);
type = !fiszero(*t)
? solve_quadric(t, &x1, &x2) : solve_linear(t + 1, &x1);
switch (type) {
case EQT_X_MANY:
puts("X has many solutions.");
break;
case EQT_X_NONE:
puts("X has no solution.");
break;
case EQT_X_LINEAR:
printf("Linear: X = %.4f.\n", x1);
break;
case EQT_X_QUADRIC:
printf("Quadric: X = %.4f, %.4f.\n", x1, x2);
break;
case EQT_X_COMPLEX:
printf("Quadric/Complex: "
"X = %.4f + %.4fi, %.4f - %.4fi.\n",
x1, x2, x1, x2
);
break;
default:
puts("ERROR: Equation type unknown!");
}
return 0;
}
int fcmp(double x, double y)
{
double diff;
diff = x && y ? (x - y) / fabs(x) : x + y;
return (diff > EPSILON) - (diff < -EPSILON);
}
int solve_linear(double t[2], double *x)
{
return fiszero(*t) ? (fiszero(t[1]) ? EQT_X_MANY : EQT_X_NONE) :
(*x = -t[1] / t[0], EQT_X_LINEAR);
}
int solve_quadric(double t[3], double *x1, double *x2)
{
double a = t[0], b = t[1], c = t[2];
double f, g;
f = b * b - 4 * a * c, g = sqrt(fabs(f)) / (2 * a);
b /= -2 * a;
*x1 = b - (fcmp(f, 0) >= 0 ? g : 0);
*x2 = g + (fcmp(f, 0) >= 0 ? b : 0);
return f >= 0 ? EQT_X_QUADRIC : EQT_X_COMPLEX;
}
int getceff(double t[3])
{
printf("Solving ax^2 + bx + c = 0.\n"
"Input (a, b, c) as type double, "
"separated by while spaces.\n"
);
if (scanf("%lf%lf%lf", t, t + 1, t + 2) < 3) {
puts("Invalid arguments. Exiting...");
exit(1);
}
printf("Equation: %.4fx^2 + %.4fx + %.4f = 0.\n\n",
t[0], t[1], t[2]);
return 0;
}
--
新詩練習:新鮮。踩破初春裡的狗大便;不經意的滄桑,滿溢著嫩黃的喜悅。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.224.161.63