Reputation: 21
I'm learning C++, and encountering these problems in a simple program, so please help me out.
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?
Upvotes: 0
Views: 1720
Reputation: 5199
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.
Upvotes: 0
Reputation: 10716
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.
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<float>(22)/7
OR
22/static_cast<float>(7)
As for why you should use static_cast - see this:
Why use static_cast<int>(x) instead of (int)x?
Upvotes: 3
Reputation: 361402
pie = (22/7);
Here the division is integer division, because both operands are 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
).
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 (i.e when even if a single operand is float
or double
).
Upvotes: 0