C++ wrong result of mathematical expression [closed]

杀马特。学长 韩版系。学妹 提交于 2019-12-02 13:27:45
Mats Petersson

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!