Division in C++ not working as expected

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?

Answers


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;

It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.

Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.

Or simply use double f=.6, that also does the trick...


try this:

double f = 3.0/5.0;

this should fix your problem


Try putting a .0 after one of the divisors. This will convert them into floating point literals.


You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.


In case, you save your generic variables with int and would like to obtain the ratio as double:

using namespace std;
int main()
{
   int x = 7;
   int y = 4;
   double ratio;
   ratio = static_cast<double>(x)/static_cast<double>(y);
   cout << "ratio =\t"<<ratio<< endl;
}

Need Your Help

how to make twitter bootstrap submenu to open on the left side?

javascript jquery css twitter-bootstrap

I was trying to create twitter bootstrap submenu in dropdown menu, but I've got a problem: I have dropdown menu in the top right corner of the page and that menu has one more submenu. However, when

Converting stream of int's to char's in java

java types

This has probably been answered else where but how do you get the character value of an int value?