[英]Float variable calculation using int error
I run the following code: 我运行以下代码:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x=4,y=2,z=11;
float p;
p=7+z/y-x*2;
cout<<p;
return 0;
}
The x, y, z is declared as integer. x,y,z声明为整数。 Why the p get an int while p is declared as float?
为什么当p声明为float时p获得一个整数?
Thanks. 谢谢。
If a and b are integers then result of a/b will always be integer, not float. 如果a和b是整数,则a / b的结果将始终是整数,而不是浮点数。 Dividing result is just truncated to integer value and float part is thrown away.
除法结果仅被截断为整数值,而浮点数则被丢弃。
In expression 7+z/yx*2
only integer variables are used, that is why result is also integer. 在表达式
7+z/yx*2
仅使用整数变量,这就是为什么结果也是整数的原因。
As an option you can cast one of the operands on right side to float, then whole expression will be threated as float: 作为一种选择,您可以将右侧的一个操作数强制转换为float,然后整个表达式将被威胁为float:
7+z/(float)y-x*2
pls change your integer datatype to float so u got 请更改您的整数数据类型为浮点数,以便
#include <iostream>
#include <string>
using namespace std;
int main()
{
float x=4,y=2,z=11;
float p;
p=7+z/y-x*2;
cout<<p;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.