Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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.

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top