c++floating-pointdivisioninteger-division

Why does division (3/5) result in zero despite being stored as a double?


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?


Solution

  • 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;