C语言 一元二次方程

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

int main() {
    float a, b, c;
    float discriminant, root1, root2;
    printf("Please enter the three coefficients of a quadratic equation with one variable:\n");
    scanf("%f %f %f", &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("This equation has two real roots:%.2f and %.2f\n", root1, root2);
    } else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("This equation has a real root:%.2f\n", root1);
    } else {
        float realPart = -b / (2 * a);
        float imagPart = sqrt(-discriminant) / (2 * a);
        printf("The equation has two imaginary roots:%.2f+%.2fi and %.2f-%.2fi\n", realPart, imagPart, realPart, imagPart);
    }
    return 0;
}

在代码设计方面仍存在以下问题:

1、未对用户输入的系数进行有效性检查,例如检查a是否为0,b和c是否为有效的浮点数。

2、当程序在计算复数根时,没有对负数求平方根的情况进行处理,可能会导致程序出现错误或崩溃。

3、在输出的结果中,根的个数可能会存在误差。例如,当判别式的值非常接近0时,可能会被误判为只有一个实根。

4、在输出结果中,根的格式化可能不够准确。例如,当输出虚部时,程序应该使用i来表示虚数单位,但可能会出现其他符号。


修改之后的代码:

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

int main() {
    float a, b, c;
    float delta, root1, root2;

    printf("Please enter the three coefficients of a quadratic equation with one variable:\n");

    // 对用户输入进行有效性检查
    if (scanf("%f %f %f", &a, &b, &c) != 3 || a == 0 || isnan(a) || isnan(b) || isnan(c)) {
        printf("Invalid input! Please enter valid coefficients.\n");
        return 1;
    }

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

    if (delta > 0) {
        root1 = (-b + sqrt(delta)) / (2 * a);
        root2 = (-b - sqrt(delta)) / (2 * a);
        printf("This equation has two real roots: %.2f and %.2f\n", root1, root2);
    } else if (delta == 0) {
        root1 = root2 = -b / (2 * a);
        printf("This equation has one real root: %.2f\n", root1);
    } else {
        float realPart = -b / (2 * a);
        float imagPart = sqrt(-delta);
        printf("This equation has two complex roots: %.2f+%.2fi and %.2f-%.2fi\n", realPart, imagPart, realPart, imagPart);
    }

    return 0;
}

这样修改之后程序执行会更加安全。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值