Division in C++ not working as expected

Psirus picture Psirus · May 23, 2011 · Viewed 64.2k times · Source

I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.

#include <iostream>

int main(int argc, char** argv)
{
  double f=3/5;
  std::cout << f;
  return 0;
}

What am I missing?

Answer

user2100815 picture user2100815 · May 23, 2011

You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:

 double f = 3.0 / 5;