1

This is really basic question, I'm testing std::cout to print float's, the following works correctly:

std::cout<<10 / 3.2<<std::endl; //Output: 3.125

But when I try:

std::cout<< 500000 / 1000000<<std::endl; //Output: 0

Why is the output of my second example not 0.5? Is this automatically rounding down?

I'm compiling with g++ -std=c++14

Babra Cunningham
  • 2,949
  • 1
  • 23
  • 50

2 Answers2

4

In your second code example 500000 and 1000000 both have integer type, so, when you divide one to another, you have integer division (the result is rounded bottom), which is 0. To fix this, try multiplying them by 1.0 or casting to any floating-point type.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
2

The compile time evaluable constant expression 500000 / 1000000 will be evaluated in integer arithmetic, which effectively means that any remainder is discarded. (Note that / has higher precedence than << so the division is evaluated first).

A clear rememdy is to promote one of the arguments to floating point (the other one is then promoted automatically by the compiler). I always pick the first one to signal to the reader of your code that you know what you're doing:

500000.0 / 1000000
Bathsheba
  • 231,907
  • 34
  • 361
  • 483