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,713
  • 4
  • 18
  • 36

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
  • 223,364
  • 34
  • 402
  • 480
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
  • 45,805
  • 12
  • 84
  • 81
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
  • 150,225
  • 13
  • 225
  • 380
0

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

faiahime
  • 37
  • 1
  • 9