因此,我需要一种方法来获得一天中的第二天,所以我在fmod() & gettimeofday() (Mac )上捣乱。然而,在此过程中,我得到了一些奇怪的结果:
#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
F: 5760
fmod: 5700.17
F: 5760
fmod: 5701.17
F: 5760
fmod: 5702.17
F: 5760
fmod: 5703.17
F: 5760
fmod: 5704.17
F: 5760
fmod: 5705.18
..。
那么,为什么fmodf()版本每次都给我相同的输出,其中fmod()版本给出了预期的结果(在sleep()调用之后进行更改)?我在文件里漏掉了什么吗?
发布于 2012-04-20 01:58:10
单精度浮标没有足够的精度来存储(t.tv_sec) + (t.tv_usec / 1000000)中的所有位。如果你等得够久(大约2分钟),你就会看到一个大跳跃。
https://stackoverflow.com/questions/10239125
复制相似问题