题解 | #计算一元二次方程#
计算一元二次方程
https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
double类型的一些特殊取值是运行double类型算出-0.0的值的,在本题的测试用例中:4 0 0,就产生-0.0的输出,其实-0.0和0.0比较是相等的,为了避免出现这个问题需要特殊处理一下,和题目要求的结果保持一致。
参考:https://zh.cppreference.com/w/c/language/arithmetic_types
参考代码如下:
#include <stdio.h> #include <math.h> int main() { double a = 0.0, b = 0.0, c = 0.0; while (3 == scanf("%lf %lf %lf", &a, &b, &c)) { double x1 = 0, x2 = 0; if (a == 0.0) printf("Not quadratic equation\n"); else { double disc = b * b - 4 * a * c; if (disc == 0.0) { //避免-0.0的问题 if (b == 0.0) { x1 = x2 = 0.0; printf("x1=x2=%.2lf\n", x1); } //有2个相等的跟 else { x1 = x2 = (-b) / (2 * a); printf("x1=x2=%.2lf\n", x1); } } else if (disc > 0.0) { //有2个实根,不等 x1 = (-b - sqrt(disc)) / (2 * a); x2 = (-b + sqrt(disc)) / (2 * a); printf("x1=%.2lf;x2=%.2lf\n", x1, x2); } else { //有两个虚跟 double real = -b / (2 * a); double image = sqrt(-disc) / (2 * a); printf("x1=%.2lf-%.2lfi;x2=%.2lf+%.2lfi\n", real, image, real, image); } } } return 0; }#C语言##一元二次方程#