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?

1
  • This. Commented Mar 10, 2013 at 7:09

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.