C ++数学表达式的错误结果 [英] C++ wrong result of mathematical expression

查看:43
本文介绍了C ++数学表达式的错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须计算一些简单的数学表达式,但是当我一行执行时,结果始终为零.但是正确的结果显然不是零.它很有趣,但是当我分开表达的各个部分时,我得到了正确的答案.稍后,我将结果除以,因此不应为0.

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.

表达式是这样的:

(X-X1)/(X2-X1)

在这种情况下,增量:0

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

但是这样 delta 是正确的:

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

您有什么想法,这怎么会发生?

Do you have any idea, how could this happen?

推荐答案

这是用于产生浮点值的整数除法"的典型情况.如果 x x1 x2 都是整数,则编译器应根据C和C ++的规则使用整数计算来计算 x-x1 x2-x1 ,然后将它们的差值除以整数除法.如果 x2-x1 大于 x-x1 ,则结果为零[假设正值为7/14.-14/-7显然是2].

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

这篇关于C ++数学表达式的错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆