2016-03-02 92 views
-3

我遇到的问题与下面的代码:C++二次代码错误

#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; 
} 

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

+2

也许你可以告诉我们什么输入会给出什么错误的输出。 –

+0

输入是: 6 -10 -4 但输出似乎是: 6 -10 -4 -0.333333 2 2 6 9 - 0.333333 2 2 4 8 -0.333333 2 0 2 4 -0.333333 2 2 4 2 2 -0.333333 通过佩耶W. Kialain 按编码任意键继续。 。 。 –

+0

一些最新出现错误的细节:[为什么浮点数不准确?](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-incucurate) – user4581301

回答

1

陈述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 s,则结果为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; 
} 
+0

感谢您的帮助!但是,我不确定如何结合epsilon常数而不会使任何事情复杂化;并且会阻止代码为每个root1和root2值赋予相同的值? –

+0

将'epsilon'方法看作'some_float == 0'的“安全”版本。我不明白它会如何使任何事情复杂化。你必须自己尝试一下。如果您不能为烦琐或害怕进行实验和迭代而无法进行编程。 – Nard