c语言相关问题,需要在程序中判别

问题遇到的现象和发生背景

img

我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%
#include 
#include 

int main() {
    double a, b, c, discriminant, root1, root2;

    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);

    discriminant = b * b - 4 * a * c;

    if (discriminant >= 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);

        printf("Roots are: %.2lf and %.2lf", root1, root2);
    } else {
        printf("No real roots");
    }

    return 0;
}

这个题目太简单了,我以自己的思路稍微优化一下你的代码吧
用户输入错误处理:在输入系数时,应当判断用户输入的数值是否合法,例如b和c不能同时为0等。此外,当输入非数字时,scanf函数会产生错误,可以使用feof函数判断是否到达文件结尾,如果没有到达文件尾部,则输出错误提示并要求重新输入。


#include <stdio.h>
#include <math.h>

double calculateDiscriminant(double a, double b, double c) {
    return b * b - 4 * a * c;
}

int main() {
    double a, b, c, delta, x1, x2;

    printf("Please enter coefficients a, b, c: ");
    if (scanf("%lf%lf%lf", &a, &b, &c) != 3 || a == 0) {
        printf("Invalid input, please try again.\n");
        return -1;
    }

    delta = calculateDiscriminant(a, b, c);
    if (delta >= 0) {
        x1 = (-b + sqrt(delta)) / (2 * a);
        x2 = (-b - sqrt(delta)) / (2 * a);
        printf("This equation has two roots: x1 = %.2lf, x2 = %.2lf\n", x1, x2);
    } else {
        printf("This equation has no real roots.\n");
    }

    return 0;
}