从浮点到整数的转换
我有以下简单算法来计算二次方程的根
#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和零,这当然不是真的,请帮助我
i have following simpled algorithm for calculation roots of quadratic equation
#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;
}
but it gives me warning
arning C4244: '=' : conversion from 'int' to 'float', possible loss of data
and when i enter -6 and 9 it gives that roots are 6 and zero which of course is not true please help me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
^
是按位异或运算符,而不是您可能认为的幂。要将数字求任意幂,请使用std::pow
(来自标准头cmath
)。对于 2 的幂,您可以只使用x * x
。^
is the bitwise xor operator, not the power, as you probably think. To raise a number to an arbitrary power, usestd::pow
(from the standard headercmath
). For powers of two, you can just usex * x
.b^2 意味着使用 XOR 运算符,我认为这不是您想要使用的。尝试使用 b*b。此外,将 a、b 和 c 声明为浮点数而不是整数可能会有所帮助。
b^2 means to use the XOR operator, which I don't think is what you meant to use. Try using b*b. Also it might be helpful to declare a, b, and c as floats and not ints.
除了对异或运算的正确注释之外,
您不能对 int 进行所有计算,然后将其转换为 float。这样 div 结果就被四舍五入了。尝试像 (float)b 一样在计算过程中强制转换 b。或将所有 a、b、c 和 d 定义为浮点数
besides the correct remarks on the xor operation
you cannot do all the calculations on int and then cast it to float. this way the div result is rounded. try to cast b in the middle of the calculation like (float)b. or define all a,b,c and d as floats
^ 是按位异或运算符,即编译器给出警告的原因。尝试使用 math.h 头文件中声明的 pow 函数。
^ is a bitwise xor operator i.e why the compiler is giving warning.Try using pow function declared in math.h header file.