[英]Float variable in C++
I'm learning C++, and encountering these problems in a simple program, so please help me out. 我正在学习C ++,并且在一个简单的程序中遇到了这些问题,所以请帮帮我。
This is the code 这是代码
#include<iostream>
using std::cout;
int main()
{ float pie;
pie = (22/7);
cout<<"The Value of Pi(22/7) is "<< pie<<"\n";
return 0;
}
and the output is 输出是
The Value of Pi(22/7) is 3
Why is the value of Pi not in decimal? 为什么Pi的值不是十进制?
That's because you're doing integer division . 那是因为您正在执行整数除法 。
What you want is really float division: 您真正想要的是浮点除法:
#include<iostream>
using std::cout;
int main()
{
float pie;
pie = float(22)/7;// 22/(float(7)) is also equivalent
cout<<"The Value of Pi(22/7) is "<< pie<<"\n";
return 0;
}
However, this type conversion: float(variable)
or float(value)
isn't type safe. 但是,这种类型转换:
float(variable)
或float(value)
不是类型安全的。
You could have gotten the value you wanted by ensuring that the values you were computing were floating point to begin with as follows: 您可以通过确保要计算的值是浮点数来获得所需的值,如下所示:
22.0/7
OR 要么
22/7.0
OR 要么
22.0/7.0
But, that's generally a hassle and will involve that you keep track of all the types you're working with. 但是,这通常很麻烦,并且涉及到跟踪所使用的所有类型。 Thus, the final and best method involves using static_cast :
因此, 最终的最佳方法涉及使用static_cast :
static_cast<float>(22)/7
OR 要么
22/static_cast<float>(7)
As for why you should use static_cast - see this: 至于为什么要使用static_cast-请参阅以下内容:
Why use static_cast<int>(x) instead of (int)x? 为什么使用static_cast <int>(x)代替(int)x?
pie = (22/7);
Here the division is integer division, because both operands are int
. 这里的除法是整数除法,因为两个操作数都是
int
。
What you intend to do is floating-point division: 您打算做的是浮点除法:
pie = (22.0/7);
Here 22.0
is double
, so the division becomes floating-point division (even though 7
is still int
). 在这里
22.0
是double
,因此除法成为浮点除法(即使7
仍然是int
)。
The rule is that IF both operands are integral type (such as int
, long
, char
etc), then it is integer division, ELSE it is floating-point division (ie when even if a single operand is float
or double
). 规则是,如果两个操作数均为整数类型(例如
int
, long
, char
等),则为整数除法,否则为浮点除法(即,即使单个操作数为float
或double
)。
Use: 采用:
pi = 22/7.0
If u give the two operands to the / operator as integer then the division performed will be integer division and a float will not be the result. 如果u将两个操作数作为整数提供给/运算符,则执行的除法将是整数除法,而浮点数将不是结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.