二次方程求解器以未知格式输出

时间:2019-05-20 16:07:20

标签: c++

我正在尝试制作二次方程式求解器,但是由于某种原因,我的程序给了我未知格式的答案。

我输入了简单的二次方程x ^ 2 + 2x + 1 = 0,期望我的程序给出x = -1或x = -1,但是相反它给出了x = 0138151E或x = 0138152D。看起来它为任何输入输出了x的这些值(无法识别并捕获不真实的答案)。为什么会这样,我该如何解决?

#include "../std_lib_facilities_revised.h"

class Imaginary {};

double square(int a)
{
    return a * a;
}

double quadratic_solver_pos(int a, int b, int c)
{
    double x = 0.0;
    double radicand = square(b) - 4 * a * c;
    if (radicand < 0) throw Imaginary{};
    x = (-b + sqrt(radicand)) / (2 * a);
    return x;
}

double quadratic_solver_neg(int a, int b, int c)
{
    double x = 0.0;
    double radicand = square(b) - 4 * a * c;
    if (radicand < 0) throw Imaginary{};
    x = (-b - sqrt(radicand)) / (2 * a);
    return x;
}

int main()
try {
    cout << "This program is a quadratic equation solver.\n";
    cout << "Quadratic equations are of the form: ax^2 + bx + c = 0\n";
    cout << "Enter a, b, and c, respectively:\n";
    double a = 0; 
    double b = 0;
    double c = 0;
    cin >> a >> b >> c;
    cout << "Your quadratic equation: " << a << "x^2 + " << b << "x + " << c << " = 0\n";
    cout << "x = " << quadratic_solver_pos << " or x = " << quadratic_solver_neg << '\n';
}
catch (Imaginary) {
    cout << "x is unreal\n";
}

1 个答案:

答案 0 :(得分:1)

您不会将变量传递给函数。

您需要这样做quadratic_solver_pos(a, b, c);