问题:
#include <stdio.h> #include <math.h> int main() { double a, b, c, x1, x2, i1, i2, san;//san求根的▲ x1<x2 scanf("%lf %lf %lf", &a, &b, &c); if (a == 0 && b == 0 && c != 0) printf("Not An Equation"); if (a == 0 && b == 0 && c == 0) printf("Zero Equation"); san = b * b - 4 * a * c; if (a == 0 && b != 0 && c != 0) { x1 = -c / b; printf("%.2f", x1); } //if (2 * a != 0) { if (san == 0 && a != 0) { x1 = -b / (2 * a); printf("%.2f", x1); } else if (san > 0) { x1 = (-b - sqrt(san)) / (2 * a); x2 = (-b + sqrt(san)) / (2 * a); printf("%.2f\n%.2f", x2, x1); } else { i1 = sqrt(-san) / (2 * a); x1 = x2 = -b / (2 * a); if (x1 != 0)printf("%.2f+%.2fi\n%.2f-%.2fi", x1, i1, x2, i1); else { x1 = -x1; x2 = -x2; printf("%.2f+%.2fi\n%.2f-%.2fi", x1, i1, x2, i1); } } return 0; }
当输入0 0 0 时,按理应该输出“Zero Equation”
但是这个代码输出的是“Zero Equation-nan(ind)+-nan(ind)i-nan(ind)--nan(ind)i” 后面多了很多奇奇怪怪的东西
INF表示“无穷大”,是infinite的缩写。
NAN表示“无效数字”,是Not a number的缩写。 也就是说代码中发生了除以0的情况
当输入0 0 0,这时的san为0,进入了最后的那个else{ }里面
else { x1 = -x1; x2 = -x2; printf("%.2f+%.2fi\n%.2f-%.2fi", x1, i1, x2, i1); }
要输出 x1 i1 x2 i2 但是a=0
i1 = sqrt(-san) / (2 * a); x1 = x2 = -b / (2 * a);
x1 x2 i1 i2都不存在 且printf中x1 x2 对应的是%d i1 i2对应的是%.2f 所以就会输出“ nan ” 和 “ inf ” 所以在前面要用if语句来限定一下a!=0