C ++ fmod为fmod(0.6,0.2)返回0.2 [英] c++ fmod returns 0.2 for fmod(0.6,0.2)

查看:173
本文介绍了C ++ fmod为fmod(0.6,0.2)返回0.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在c ++中使用fmod(0.6,0.2)时,它返回0.2

when I use fmod(0.6,0.2) in c++ it returns 0.2

我知道这是由浮点精度引起的,但是现在看来我得剩下两倍的余数

I know this is caused by floating point accuracy but it seems I have to get remainder of two double this moment

非常感谢您为此类问题提供的解决方案

thanks very much for any solutions for this kind of problem

推荐答案

数学值0.60.2不能用二进制浮点数精确表示.

The mathematical values 0.6 and 0.2 cannot be represented exactly in binary floating-point.

此演示程序将向您显示正在发生的事情:

This demo program will show you what's going on:

#include <iostream>
#include <iomanip>
#include <cmath>
int main() {
    const double x = 0.6;
    const double y = 0.2;
    std::cout << std::setprecision(60)
              << "x          = " << x << "\n"
              << "y          = " << y << "\n"
              << "fmod(x, y) = " << fmod(x, y) << "\n";
}

我的系统(很可能是您的系统)上的输出是:

The output on my system (and very likely on yours) is:

x          = 0.59999999999999997779553950749686919152736663818359375
y          = 0.200000000000000011102230246251565404236316680908203125
fmod(x, y) = 0.1999999999999999555910790149937383830547332763671875

fmod()返回的结果在给定传递参数的情况下是正确的.

The result returned by fmod() is correct given the arguments you passed it.

如果您需要其他结果(我想您期望的是0.0),则必须做一些不同的事情.有很多可能性.您可以检查结果是否与0.2相差很小,或者可以使用整数算术进行计算(例如,如果要处理的所有数字都是0.10.01).

If you need some other result (I presume you were expecting 0.0), you'll have to do something different. There are a number of possibilities. You can check whether the result differs from 0.2 by some very small amount, or perhaps you can do the computation using integer arithmetic (if, for example, all the numbers you're dealing with are multiples of 0.1 or of 0.01).

这篇关于C ++ fmod为fmod(0.6,0.2)返回0.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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