C++二次码错误

C++ Quadratic Code Errors

本文关键字:二次 错误 C++      更新时间:2023-10-16

我在下面的代码中遇到了问题:

#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;
int main()
{
    ifstream fin("input.txt");
    ofstream fout("output.txt");
    float discriminant, A, B, C, root1, root2;
    fin >> A >> B >> C;
    while (A != -99)
    {
        discriminant = (pow(B, 2.0) - 4 * A*C);
        if (A == 0)
        {
            fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
        }
        else if (discriminant > 0)
        {
            root1 = (-B - sqrt(discriminant)) / (2.0*A);
            root2 = (-B + sqrt(discriminant)) / (2.0*A);
            fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
        }
        else if (discriminant == 0)
        {
            fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
        }
        else
        {
            fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
        }
        fin >> A >> B >> C;
    }
    fout.close();
    ifstream fin2("output.txt");
    fin2 >> A >> B >> C >> root1 >> root2;
    while (!fin2.eof())
    {
        cout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
        fin2 >> A >> B >> C >> root1 >> root2;
    }
    cout << endl;
    cout << "Coded by Paye W. Kialain" << "t"<< endl;
    system("pause");
    return 0;
}

在项目描述中,我被告知创建一个包含 a、b 和 c 的输入文件,我做到了。输出的格式也正确。它是一个显示 a、b 和 c 值以及 2 个计算根的表格。然而,根的计算似乎不对。我的 if 语句是问题吗?

语句 discriminant == 0A == 0 是危险的比较,因为discriminantAfloat s。 浮点计算通常伴随着浮点误差(想想你在数学近似中得到的错误)。

考虑这个浮点错误的简单示例:

#include <iostream>
#include <string>
int main()
{
  float a = 3.0;
  float b = 10.0;
  std::cout.precision(20);
  std::cout << a/b << std::endl;
}

3.0/10.0,这是初级数学!您希望结果为 0.3。但是,事实证明,结果是 0.30000001192092895508。如果ab double,则结果将为 0.2999999999999999889。这是因为浮点数以二进制表示的方式不允许准确表示 0.3。现在想象一下,如果我有像if(a/b == 0.3)这样的代码会发生什么。条件永远不会得到满足。

此问题的解决方案是引入 epsilon 值。此 epsilon 值基本上用作容错值。

float a = 3.0;
float b = 10.0;
const float epsilon = 0.000001;
if(fabs(a/b - 0.3) < epsilon) {
  std::cout << "a/b is equal to 0.3!" << std::endl;
}