1.今天试着找了一下附带判断语句的二次方程求解程序,也对if 语句的使用有一个初步认识
2.对于判断disc=b2-4ac是否等于0时 ,要注意实数在计算和储存时会有一些微小的误差,因此不能直接进行”if(disc==0)……“ 因为这样会出现本来是0的量,因为上述误差二被判断为不等于零从而导致错误
3.最好的办法就是判别disc的绝对值是否小于一个很小的数(e-6),如果小于此数,就认为disc等于0
4.对于2、3描述,确实有点难理解,本来是0的量为何会被判别为不等于零,有没有大神举个例子解答一下,感激不尽!
#include<stdio.h> #include<math.h> int main() { ?? ?double a, b, c, disc, x1, x2, realpart, imagpart; ?? ?scanf_s("%lf,%lf,%lf",&a,&b,&c); ?? ?printf("The equation"); ?? ?if (fabs(a) <= 1e-6) ?? ??? ?printf("is not a quadratic\n"); ?? ?else ?? ?{ ?? ??? ?disc = b*b - 4 * a*c; ?? ??? ?if (fabs(disc) <= 1e-6) ?? ??? ??? ?printf("has two equal roots:%8.4\n", -b / (2 * a)); ?? ??? ?else ?? ??? ??? ?if (disc > 1e-6) ?? ??? ??? ?{ ?? ??? ??? ??? ?x1 = (-b+sqrt(disc)) / (2 * a); ?? ??? ??? ??? ?x2 = (-b - sqrt(disc)) / (2 * a); ?? ??? ??? ??? ?printf("has two distinct real roots:%8.4f and %8.4f\n",x1,x2); ?? ??? ??? ?} ?? ??? ??? ?else ?? ??? ??? ?{ ?? ??? ??? ??? ?realpart = -b / (2 * a); ?? ??? ??? ??? ?imagpart = sqrt(-disc) / (2 * a); ?? ??? ??? ??? ?printf("has complex roots;\n"); ?? ??? ??? ??? ?printf("%8.4f+%8.4fi\n",realpart,imagpart); ?? ??? ??? ??? ?printf("%8.4f-%8.4fi\n", realpart, imagpart);
?? ??? ??? ?} ?? ?} ?? ? ?? ?return ?0; ?? ??? ? } ??
|