c++ - 为什么整数的下限不等于自身(cpp)?

标签 c++

我有一个 double 和一个 int 变量。他们的产品是一个整数。我想检查一下,所以我关注了 this方法,真是百思不得其解……

当我这样做时,一切都像它应该的那样:

#include <cmath>

double a = 0.1;
int b = 10;
double product = a * (double) b;

if(std::floor(product) == product){
    // this case is true
else{
    // this case is false
}

但是,奇怪的是,这不起作用:

#include <cmath>

double a = 0.1;
int b = 10;

if(std::floor(a * (double) b) == (a * (double) b)){
    // this case is false
else{
    // this case is true
}

谁能给我解释一下?


编辑:

澄清一下,这不仅仅是固定精度浮点计算的问题:

#include <cmath>

double a = 0.1;
int b = 10;

if((a * (double) b) == (a * (double) b)){
    // this case is true
else{
    // this case is false
}

所以 ab 的乘积(虽然不精确等于 1.0)当然等于它本身,但是调用 std::floor() 把事情搞砸了。

最佳答案

这是由于舍入误差造成的。

首先,0.1 不能精确地存储在 double 中,因此您的 product 很可能不完全是 1。

其次,我认为,更重要的是,在你的情况下,还有一个更微妙的原因。当您直接比较某些计算的结果而不是将它们存储到 double 变量中并比较它们时(if (cos(x) == cos(y)) 而不是 a=cos(x); b=cos(y); if (a==b)...), 你可能会发现 operator== 返回 false 即使 x==y。原因在这里得到了很好的解释:https://isocpp.org/wiki/faq/newbie#floating-point-arith2 :

Said another way, intermediate calculations are often more precise (have more bits) than when those same values get stored into RAM. <...> Suppose your code computes cos(x), then truncates that result and stores it into a temporary variable, say tmp. It might then compute cos(y), and (drum roll please) compare the untruncated result of cos(y) with tmp, that is, with the truncated result of cos(x)

乘法可能会产生相同的效果,因此您的第一个代码可以工作,但第二个代码不行。

关于c++ - 为什么整数的下限不等于自身(cpp)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30119778/

相关文章:

C++ 运算符重载流需要转换

c++ - 使用转换填充 vector 后,新的 c++11 for 循环不起作用

c++ - 程序过早结束,可能已经崩溃。退出代码 0xc0000005

C++ 帮助 : loops and switches

c++ - 无法为托管代码运行非托管 cpp 单元测试

c++ - 模板表达式如何摆脱临时变量

c++ - boost 多边形差异返回交集

c++ - 在类中获取指向自身的指针

python - Cython:将字符值转换为字符串的最快方法

c++ - 错误 : Expression must have integral or unscoped enum type