计算二次方程的根。 C ++

时间:2014-12-13 18:34:44

标签: c++ equation quadratic

我想计算二次方程ax2 + bx + c = 0的根。我认为我的算法是正确的,但我不熟悉函数,我认为我的错误是调用它们。你可以帮帮我吗?先感谢您。这是代码。

#include<iostream>
#include<cmath>
using namespace std;
const double EPS = 1.0e-14;
int quadraticEquation(int& a,int& b, int& c)

{
    if(abs(a) < EPS)
    {
        if(abs(b) < EPS)
        {
            cout << "No solution" << endl;
        }
        else
        {
            double x = - c /b ;
            cout << "One root: " << x << endl;
        }
    }
    else
    {
        double delta = b * b - 4 * a * c;
        if(delta < 0)
        {
            cout << "No solution:\n" ;
        }
        else
        {
            double square_delta = sqrt(delta);
            double root_1 = (-b + square_delta) / (2 * a);
            double root_2 = (-b - square_delta) / (2 * a);
            cout << "x1 = " << root_1 << endl;
            cout << "x2 = " << root_2 << endl;
        }
    }

}

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;
    cout << "The solution is: " << quadraticEquation(int a,int b,int c);

    return 0;
}

3 个答案:

答案 0 :(得分:3)

应该是:

cout << "The solution is: " << quadraticEquation(a, b, c); // no types in calling a function

答案 1 :(得分:2)

问题并非如此,erenon和Paco Abato确实回答了C ++问题。

但是你的算法还有一些改进:

  • abs(a)&lt; EPS和abs(b)&lt; EPS - 如果abc(c)&lt; EPS每个x都是解决方案
  • 如果delta < 0应为if delta <= (-EPS)
  • 您忘了if abs(delta) < EPS)一个双重解决方案:double x = - b / a;

答案 2 :(得分:-1)

将函数定义为:

int quadraticEquation(int a,int b, int c)

没有&amp;标志通过价值而不是通过参考传递参数(尽管juanchopanza在评论中表示并非严格要求)。

并将其命名为:

cout << "The solution is: " << quadraticEquation( a, b, c);

没有int因为在函数调用中你不能提供参数的类型。

相关问题