【问题标题】:C++: fmodf() & fmod() - Strange Results?C++:fmodf() & fmod() - 奇怪的结果?
【发布时间】:2012-04-20 01:40:42
【问题描述】:

所以,我需要一种方法来获得当天的第二天,所以我搞砸了 fmod()gettimeofday() (Mac OSX)。然而,我在此过程中遇到了一些奇怪的结果:

#include <iostream>

#include <sys/time.h>
#include <cmath>

class A {
public:
    static float secondOfDayFmodF()
    {
        timeval t;
        gettimeofday(&t, NULL);

        return fmodf((t.tv_sec) + (t.tv_usec / 1000000.0), 86400);
    }

    static float secondOfDayFmod()
    {
        timeval t;
        gettimeofday(&t, NULL);

        return fmod(((t.tv_sec) + (t.tv_usec / 1000000.0)), 86400);
    }
};

using namespace std;

int main(int argc, const char *argv[])
{    
    for (int i = 0; i < 100; i++)
    {
        cout << "fmodf:\t" << A::secondOfDayFmodF() << endl;
        cout << "fmod:\t"  << A::secondOfDayFmod()  << endl;

        // sleep for 1 s
        sleep(1);
    }

    getchar();
}

输出:

fmodf: 5760
fmod:5699.17
fmodf: 5760
fmod:5700.17
fmodf: 5760
fmod:5701.17
fmodf: 5760
fmod:5702.17
fmodf: 5760
fmod:5703.17
fmodf: 5760
fmod:5704.17
fmodf: 5760
fmod:5705.18
...

那么,为什么fmodf() 版本每次都给我相同的输出,而fmod() 版本给出了预期的结果(在sleep() 调用之后发生变化)?我在文档中遗漏了什么吗?

【问题讨论】:

标签: c++ posix modulo gettimeofday


【解决方案1】:

单精度浮点数没有足够的精度来存储(t.tv_sec) + (t.tv_usec / 1000000) 中的所有位。如果你等待的时间足够长(大约 2 分钟),你会看到一个很大的跳跃。

【讨论】:

  • 天哪,天哪,你是对的!这很有趣,感谢您的洞察力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
相关资源
最近更新 更多