下面的代码应该读取二次方程的 3 个系数并输出判别式和解(如果有的话),类似于这个在线计算器:https://calculator.tutorvista.com/math/496/2nd-degree-equation-calculator.html 但出于某种原因,我的计算器似乎在某些情况下可以正确得出一些结果,但在大多数情况下却不能。
#include <iostream>
#include <math.h>
using namespace std;
int main() {
float a, b, c;
cout << "a=" << endl;
cin >> a;
cout << "b=" << endl;
cin >> b;
cout << "c=" << endl;
cin >> c;
float delta = (pow(b, 2)) - (4 * a*c);
float summit = (-b) / (2 * a);
float x1 = (-(b) + (sqrt(delta)) / (2 * a));
float x2 = (-(b) - (sqrt(delta)) / (2 *a));
cout <<"Discriminant="<< delta << endl;
if (delta < 0) {
cout << "No solution" << endl;
}
else if (delta == 0) {
cout << "Unique solution is:" << summit << endl;
}
else {
cout << "First solution is:" << x1 << endl;
cout << "Second solution is:" << x2 << endl;
}
std::cin.ignore();
std::cin.get();
}
根据上面链接的在线计算器,这里有一些罕见的输入示例,我的计算器按预期工作:
a=3;b=1;c=24;
a=1;b=0;c=0;
a=1;b=-4;c=4;
但事情并不总是那么顺利,例如输入 1;4;-12 给你 8 和 0 而不是 6 和 -2(注意结果如何偏离 2),在其他情况下之一解决方案将是正确的,而另一个则不会,而且大多数时候结果完全不对。
我不确定问题出在判别式还是解,因为有时前者是正确的而后者不是。
在用 C++ 编写数学公式时,是否有我不知道的特定礼仪?
提前致谢。
最佳答案
公式是 ( -b +- sqrt(D) )/2a ,
但你计算 -b +- 开方(D)/2a,
因为除法优先于加法/减法,所以你的行
float x1 = (-(b) + (sqrt(delta)) / (2 * a) );
float x2 = (-(b) - (sqrt(delta)) / (2 * a) );
应该是
float x1 = (-(b) + sqrt(delta)) / (2 * a);
float x2 = (-(b) - sqrt(delta)) / (2 * a);
关于c++ - 二次多项式计算器的输出不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954655/