You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现二次方程计算器求根结果错误问题求助

二次方程计算器计算结果错误修复

问题描述

测试自行编写的二次方程计算器代码时,针对方程x² + 5x + 6的计算无法输出正确答案,对应运行结果可查看截图:
x²+5x+6运行结果截图

原实现代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
        
double roots() {
    double a, b, c, x1, x2;
    cout << "Enter quadratic equation in order (a, b, c): \n";
    cin >> a >> b >> c;
    double discriminant = b * b - 4 * a * c;
    x1 = -b + sqrt(discriminant) / 2 * a;
    x2 = -b - sqrt(discriminant) / 2 * a;
    
    if (discriminant >= 0 && a > 1) {
        cout << "Your quadratic equation is " << a << "x^2 + " << b << " x + " << c << '\n';
        cout << "x1 = " << x1 << '\n';
        cout << "x2 = " << x2 << '\n';
    }
    else if (a == 1) {
        cout << "Your quadratic equation is " << "x^2 + " << b << " x + " << c << '\n';
        cout << "x1 = " << x1 << '\n';
        cout << "x2 = " << x2 << '\n';
    }
    else {
        cout << "Negative value returned from (b2 - 4ac), please try again!";
        exit(1);
    }
}
    
int main() {
    roots();
}

错误点说明

  • 求根公式运算顺序错误:标准二次方程求根公式为 $x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}$,代码中sqrt(discriminant) / 2 * a按照C++从左到右的乘除运算优先级,实际执行逻辑是(sqrt(discriminant)/2)*a,没有把-b±sqrt(discriminant)作为整体分子、2*a作为整体分母计算。以x²+5x+6(即a=1,b=5,c=6,判别式为1)为例,现有代码计算x1时得到-5 + 1/2*1 = -4.5,和正确根-2完全不符。
  • 分支判断逻辑错误:现有判断把a>1和判别式非负绑定,只要a不等于1、也不大于1,就会直接判定为判别式为负,完全遗漏了0<a<1、a为负数等合法二次方程场景,逻辑覆盖不全。
  • 语法规范问题:代码中直接使用cout、cin、sqrt、exit等标准库函数,未添加std::命名空间前缀,无对应命名空间声明时无法正常编译;roots函数声明返回值为double,但函数内无任何return语句,会触发编译警告。

修正后代码

#include <iostream>
#include <cmath>
#include <cstdlib>

double roots() {
    double a, b, c, x1, x2;
    std::cout << "Enter quadratic equation in order (a, b, c): \n";
    std::cin >> a >> b >> c;

    // 排除a=0的非二次方程场景
    if (a == 0) {
        std::cout << "a cannot be 0, input is not a quadratic equation!\n";
        exit(1);
    }

    double discriminant = b * b - 4 * a * c;
    // 修正求根公式运算顺序,补充分母括号
    x1 = (-b + sqrt(discriminant)) / (2 * a);
    x2 = (-b - sqrt(discriminant)) / (2 * a);
    
    if (discriminant >= 0) {
        if (a == 1) {
            std::cout << "Your quadratic equation is x^2 + " << b << " x + " << c << '\n';
        } else {
            std::cout << "Your quadratic equation is " << a << "x^2 + " << b << " x + " << c << '\n';
        }
        std::cout << "x1 = " << x1 << '\n';
        std::cout << "x2 = " << x2 << '\n';
        return 0;
    } else {
        std::cout << "Negative discriminant, no real roots, please try again!\n";
        exit(1);
    }
}
    
int main() {
    roots();
    return 0;
}

修正后输入1 5 6,会正确输出x1=-2、x2=-3的结果。

内容的提问来源于stack exchange,提问作者Kimi Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 06:45:47