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

教授提供的C++代码含未定义函数getRootCount与solveEquation求助

二次方程求解程序:补全缺失函数并实现哨岗循环

教授提供的代码中,getRootCount和solveEquation是自定义函数而非C++标准库函数,因此需要自行实现;同时要将单次运行逻辑改为哨岗循环,让程序可重复处理输入直到用户触发终止条件。以下是完整可运行的代码及关键说明:

完整代码

#include <iostream>
#include <cmath> // 用于平方根函数sqrt
using namespace std;

int const SIZE = 3;

// 计算实根数量
int getRootCount(double discriminant) {
    if (discriminant > 0) {
        return 2;
    } else if (discriminant == 0) {
        return 1;
    } else {
        return 0;
    }
}

// 求解二次方程根并存储到数组
void solveEquation(double discriminant, double coefficients[], double roots[]) {
    double a = coefficients[0];
    double b = coefficients[1];
    if (discriminant == 0) {
        roots[0] = -b / (2 * a);
    } else {
        roots[0] = (-b + sqrt(discriminant)) / (2 * a);
        roots[1] = (-b - sqrt(discriminant)) / (2 * a);
    }
}

int main() {
    double coefficients[SIZE];
    double discriminant;

    // 哨岗循环:以-999为终止信号
    while (true) {
        cout << "This program solves quadratic formulas" << endl;
        cout << "Enter 3 coefficients separated by spaces (enter -999 as first coefficient to quit): ";
        cin >> coefficients[0];

        // 触发哨岗条件,退出程序
        if (coefficients[0] == -999) {
            cout << "Exiting program..." << endl;
            break;
        }
        cin >> coefficients[1] >> coefficients[2];

        if (coefficients[0] == 0) {
            cout << "First coefficient cannot be 0." << endl;
        } else {
            // 计算判别式b²-4ac
            discriminant = coefficients[1] * coefficients[1] - 4 * coefficients[0] * coefficients[2];
            int rootCount = getRootCount(discriminant);
            
            if (rootCount == 0) {
                cout << "There is no real root" << endl;
            } else {
                double roots[2];
                solveEquation(discriminant, coefficients, roots);
                if (rootCount == 1) {
                    cout << "There is one root: " << roots[0] << endl;
                } else {
                    cout << "There are 2 roots: " << roots[0] << "   " << roots[1] << endl;
                }
            }
        }
        cout << endl; // 分隔每次计算的输出
    }
    return 0;
}

关键改动说明

  • 补全自定义函数:
    • getRootCount:根据判别式的值,返回对应的实根数量(2个不等实根、1个重根、0个实根)
    • solveEquation:基于判别式和二次项系数计算根,结果存入传入的数组;需引入<cmath>头文件调用sqrt函数
  • 实现哨岗循环:
    • 用while(true)构建无限循环,将第一个系数输入-999设为终止触发条件
    • 调整输入提示,明确告知用户终止方式
  • 修复原代码缺陷:
    • 原代码中discriminant未赋值,现在在处理有效系数时先计算判别式
    • 优化无实根的提示文本,表述更精准

内容的提问来源于stack exchange,提问作者Nolan Van Schmus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:00:57