-2

I have to calculate some simple mathematical expression, but when I do it in one row, the result always will be zero. But the correct result is obviously not zero. And its interesting but when I separate the parts of expression, I get the correct answer. Later I will divide with this result, so it should not be 0.

The expression is like this:

(X-X1)/(X2-X1)

In this case the delta: 0

double delta = (x - x1) / (x2 - x1);

But this way the delta will be correct:

double top = x - x1;
double bottom = x2 - x1;
double delta = top/bottom;

Do you have any idea, how could this happen?

Steve M. Bay
  • 313
  • 1
  • 3
  • 15

4 Answers4

11

This is a typical case of "integer division used to make a float value". If x, x1 and x2 are all integers, then the compiler should, according to the rules of C and C++ use integer calculations to calculate x-x1 and x2-x1, and then divide the differences of those as integer division. If x2-x1 is greater than x-x1, then the result is zero [assuming positive values like 7/14. -14 / -7 is obviously 2].

The easy fix is to convert the type of one expression to a floating point type:

double delta = static_cast<double>(x - x1) / (x2 - x1);
Bill
  • 14,257
  • 4
  • 43
  • 55
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • 1
    And by "integer division" it is meant that the answer is truncated, that is, the whole part of the answer is kept and the remainder is discarded. So `1/2` gives 0 with a remainder of 1 which is thrown out, giving `1 / 2 == 0`. – Reinstate Monica -- notmaynard Mar 21 '13 at 14:53
  • Thanks a lot, I understood the problem. (I did not know how to describe my problem well, thats why I asked the question.) – Steve M. Bay Mar 21 '13 at 14:56
2

In the first case, integer / integer, result is still integer, then convert integer to double.

In the second case, double / double, then you get correct result.

TieDad
  • 9,143
  • 5
  • 32
  • 58
1

In the first case, you are performing int / int which will result in a int value. So, if your denominator is larger than the numerator, the result will be truncated to 0.

In the second case, you are evaluating a double/double expression which will evaluate to a double value, hence preserving the fractional and integer parts.

asheeshr
  • 4,088
  • 6
  • 31
  • 50
0

You have to cast the integer division to double. type casting

andre_lamothe
  • 2,171
  • 2
  • 41
  • 74