0

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?

prabuksara
  • 21
  • 4
  • [This.](http://stackoverflow.com/questions/15319690/c-char-and-cin#comment21629645_15319690) –  Mar 10 '13 at 07:09

3 Answers3

3

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?

Community
  • 1
  • 1
jrd1
  • 10,358
  • 4
  • 34
  • 51
0
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).

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

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.

IcyFlame
  • 5,059
  • 21
  • 50
  • 74