我尝试在C ++中编写二次方程式计算器,并且我一直遇到这个错误。看看你能否弄清楚原因: (错误发生在'g ='行)
#include <cmath>
#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f,g;
cout<<"Enter 'A' value:";
cin>>a;
cout<<"Enter'B' value:";
cin>>b;
cout<<"Enter 'C' value:";
cin>>c;
e = ((b * b) - (4 * (a*c)));
d = sqrt(e);
f = ((-b) + d) / (2 * a);
g = ((-b) - d) / (2 * a);
if(d > 0){
cout<<"One solution is: "<<f<<endl;
cout<<"The other solution is: "<< g <<endl;
}
else if(d == 0){
cout<<"Your 1 solution is: "<< f <<endl;
}
else{
cout<<"No real solutions!"<<endl;
}
}
感谢任何帮助!
答案 0 :(得分:1)
平方根函数将返回浮点值,因此您应该使用像double这样的浮点变量来存储结果。
#include <cmath>
#include <iostream>
using namespace std;
int main(){
int a,b,c,e;
double d,f,g;
cout<<"Enter 'A' value:";
cin>>a;
cout<<"Enter'B' value:";
cin>>b;
cout<<"Enter 'C' value:";
cin>>c;
e = ((b * b) - (4 * (a*c)));
d = sqrt(e);
f = ((-b) + d) / (2 * a);
g = ((-b) - d) / (2 * a);
if(d > 0){
cout<<"One solution is: "<<f<<endl;
cout<<"The other solution is: "<< g <<endl;
}
else if(d == 0){
cout<<"Your 1 solution is: "<< f <<endl;
}
else{
cout<<"No real solutions!"<<endl;
}
}
答案 1 :(得分:0)
问题是平方根函数返回浮点小数,并且您尝试将其与整数组合。例如,1 - 2.0。这两个值都必须是浮点小数,因此您应该在第5行将“int”更改为“double”。