C++ Division – Why 3/5 Results in Zero Despite Being Stored as Double

c++divisionfloating-pointinteger-division

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?

Best Answer

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;
Related Question