【发布时间】:2014-11-09 22:15:17
【问题描述】:
我是一名学习 c++ 的学生,这周我必须制作一个二次公式求解器。我应该只使用主代码块中的函数来获取输出。 这是我目前所拥有的:
#include <iostream>
#include <cmath>
using namespace std;
double a, b, c, x1, x2;
char choice, response, mychar;
double disc = (b*b - 4 * a*c);
void GetCoefficients(double a, double b, double c)
{
cout << "Enter the coefficients of your quadratic equation (a, b, c): ";
cin >> a, b, c;
}
bool ComputeRoots(double a, double b, double c, double x1, double x2)
{
if (disc > 0)
{
x1 = (-b + sqrt((b*b) - 4 * a*c)) / 2 * a;
x2 = (-b - sqrt((b*b) - 4 * a*c)) / 2 * a;
return true;
}
if(disc == 0)
{
x1 = x2 = (-1 * b) / (2 * a);
return true;
}
else
{
cout << "'a' cannot be zero. That is not a quadratic equation.";
return false;
}
}
char PromptToContinue()
{
char mychar;
cout << "Would you like to solve another quadratic equation (Y, N): ";
cin >> mychar;
return mychar;
}
void PrintRoots(double x1, double x2)
{
if (disc > 0)
{
cout << "The roots are: " << x1 << ", " << x2;
}
if (disc == 0)
{
cout << "The single root is: " << x1;
}
}
void main()
{
do
{
GetCoefficients(a, b, c);
if (ComputeRoots(a, b, c, x1, x2))
{
PrintRoots(x1, x2);
}
choice = PromptToContinue();
} while (choice != 'n' || 'N');
system("pause");
}
我确定我的代码存在多个问题,但我已经盯着这个看了好几个小时,不知道为什么它不起作用。任何见解都会很棒。
我应该得到的示例输出是这样的(冒号后面的值是用户输入):
输入二次方程 (a, b, c) 的系数:2 3 4
根源很复杂。你想解另一个二次方程(Y,N):y
输入二次方程 (a, b, c) 的系数:1 2 1单根是:-1
你想解另一个二次方程(Y,N):y
输入二次方程 (a, b, c) 的系数:0 5 6'a' 不能为零。这不是一个二次方程。
你想解另一个二次方程(Y,N):y
输入二次方程 (a, b, c) 的系数:5 25 5根是:-0.208712, -4.79129
你想解另一个二次方程(Y,N):n
按任意键继续 。 . .
我得到的输出是这样的:
Enter the coefficients of your quadratic equation (a, b, c): 2 3 4
The single root is: 0Would you like to solve another quadratic equation (Y, N):
Enter the coefficients of your quadratic equation (a, b, c): The single root is:
0Would you like to solve another quadratic equation (Y, N):
【问题讨论】:
-
你的程序输出的是什么?
-
什么不起作用?你的问题需要更具体。您应该发布输出/错误。另外,您的问题标题基本上没用。如果您提出正确的问题,您可能会自己解决问题。
-
创建一个返回双精度并计算光盘的函数。
标签: c++