0

Possible Duplicate:
Division in C++ not working as expected

Turns out my program has been returning wrong results, so I decided to break the code into little pieces. After setting breakpoint, turns out that...

double test3 = ((2 - 1) / 2);

...equals 0 according to C++ compiler. I have no idea why. Can someone explain it to me?

I'm using MS Visual Studio Premium 2012

Community
  • 1
  • 1
Paweł Duda
  • 1,683
  • 3
  • 18
  • 35

4 Answers4

5

Because you are doing integer division. 1/2 is 0, which is then converted to double, yielding 0.. If you want floating point division, try making one of the arguments of the division a floating point number:

double test3 = (2.0-1)/2;
juanchopanza
  • 216,937
  • 30
  • 383
  • 461
1

Because the numbers you used on the right hand side are all integers: (i.e.: the expression (2-1)/2 evaluates to 0 as (int)1/(int)2 evaluates to 0 since the whole thing is an integer.

Change it to:

double test3 = ((2 - 1) / 2.0);

And the expression is then (int)1/(double)2, which will evaluate to a double, and thus 0.5

sampson-chen
  • 43,283
  • 12
  • 82
  • 80
1

When only integers are involved in an expression, you will only get integer arithmetic. If you want to have floating point arithmetic, you need to involve a floating point expression at some point, e.g.

double test3 = ((2 - 1) / 2.0);
Dietmar Kühl
  • 145,940
  • 13
  • 211
  • 371
0

try making your numbers double, (2.-1.)/2.;

faiahime
  • 37
  • 1
  • 9