开发者

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 开发者_JAVA技巧0.

#include <iostream>

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

What am I missing?


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜