modf以小数形式返回1: [英] modf returns 1 as the fractional:

查看:138
本文介绍了modf以小数形式返回1:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个静态方法,它接收一个double并切割它的小数尾部,在点之后留下两位数。几乎几乎。我注意到当
收到2.3时它会变成2.29。 0.3,1.3,3.3,4.3和102.3不会发生这种情况。
代码基本上将数字乘以100使用modf将整数值除以100并返回它。
这里代码捕获了这个特定的数字并打印出来:

I have this static method, it receives a double and "cuts" its fractional tail leaving two digits after the dot. works almost all the time. I have noticed that when it receives 2.3 it turns it to 2.29. This does not happen for 0.3, 1.3, 3.3, 4.3 and 102.3. Code basically multiplies the number by 100 uses modf divides the integer value by 100 and returns it. Here the code catches this one specific number and prints out:

static double dRound(double number) {

    bool c = false;
    if (number == 2.3)
        c = true;


    int factor = pow(10, 2);
    number *= factor;


    if (c) {
        cout << " number *= factor : " << number << endl;
        //number = 230;// When this is not marked as comment the code works well.
    }


    double returnVal;
    if (c){
        cout << " fractional : " << modf(number, &returnVal) << endl;
        cout << " integer : " <<returnVal << endl;
    }


    modf(number, &returnVal);
    return returnVal / factor;
}

打印出来:

数字* =因子:230

number *= factor : 230

小数:1

整数:229

有谁知道为什么会这样,我该如何解决这个问题?
谢谢你,周末愉快。

Does anybody know why this is happening and how can i fix this? Thank you, and have a great weekend.

推荐答案

记住浮点数不能完全代表十进制数。 2.3 * 100实际上给出229.99999999999997。因此 modf 返回229和0.9999999999999716。

Remember floating point number cannot represent decimal numbers exactly. 2.3 * 100 actually gives 229.99999999999997. Thus modf returns 229 and 0.9999999999999716.

然而, cout 的格式默认只显示浮点数到6位小数。因此0.9999999999999716显示为1.

However, cout's format will only display floating point numbers to 6 decimal places by default. So the 0.9999999999999716 is shown as 1.

您可以(大致)使用值(大致)表示浮点值表示的上限错误指向避免2.3错误:

You could use (roughly) the upper error limit that a value represents in floating point to avoid the 2.3 error:

#include <cmath>
#include <limits>
static double dRound(double d) {
   double inf = copysign(std::numeric_limits<double>::infinity(), d);
   double theNumberAfter = nextafter(d, inf);
   double epsilon = theNumberAfter - d;

   int factor = 100;
   d *= factor;
   epsilon *= factor/2;
   d += epsilon;

   double returnVal;
   modf(number, &returnVal);
   return returnVal / factor;
}

结果: http://www.ideone.com/ywmua

这篇关于modf以小数形式返回1:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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