[英]conversion from float to integer
我有以下简单的算法来计算二次方程的根
#include <iostream>
#include <math.h>
using namespace std;
int main(){
float x,x1;
x=0;x1=0;
int a=1;
int b;
int c;
cout<<"enter the second term:"<<endl;
cin>>b;
cout<<"enter the third term:";
cin>>c;
float d=b^2-4*a*c;
if (d<0){
cout<<"the equation has not real solution :"<<endl;
}
else if (d==0) { x=(-b/2); x1=x;}
else
{
x=(-b+sqrt(d))/2;x1=(-b-sqrt(d))/2;
}
cout<<"roots are :"<<x<< " "<<x1<< " "<<endl;
return 0;
}
但这给了我警告
arning C4244: '=' : conversion from 'int' to 'float', possible loss of data
当我输入-6和9时,它得出的根数是6和0,这当然是不正确的,请帮助我
^
是您可能认为的按位异或运算符,而不是幂。 要将数字提升为任意幂,请使用std::pow
(来自标准标头cmath
)。 对于2的幂,可以只使用x * x
。
b ^ 2表示使用XOR运算符,我认为这不是您要使用的运算符。 尝试使用b * b。 同样,将a,b和c声明为float而不是ints可能会有所帮助。
除了关于异或运算的正确说明
您不能对int进行所有计算,然后将其强制转换为float。 这样,div结果将被四舍五入。 尝试像计算(float)b一样在计算中间投射b。 或将所有a,b,c和d定义为浮点数
^是按位异或运算符,即编译器为何给出警告。请尝试使用math.h头文件中声明的pow函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.