在我不断尝试学习C语言的过程中,我遇到了以下挫折。我正在尝试编写一个函数,返回以秒为单位的时间,但精度为毫秒,类似于Python time.time()。下面是我为实现这一点而编写的代码:
#include <stdio.h>
#include <time.h>
float getTime() {
// Get the time in seconds (with millisecond precision), e.g. 1656535840.1737888
// Get spec
struct timespec spec;
// Put the current time (ns) into spec
clock_gettime(CLOCK_REALTIME, &spec);
// Get the time and
// Jam them together to one float and return
return ((float) time(NULL)) + (((float) spec.tv_nsec) / 1000000000.0f);
}
int main() {
// Get the time
float test = getTime();
// Print it to the screen
printf("\nAssignment: %f", test);
// Let's try and make a (pretty bad) clock...
// Loop...
for (int i = 0; i < 30; i ++) {
// Print current time
printf("\nPrinting: %f", getTime());
}
return 0;
}由于没有某种类型的sleep()命令,因此计算机应使用字符串"Assignment: "将当前时间打印到屏幕上,然后立即使用字符串"Printing: "继续打印时间。因此,它应该打印如下内容:
Assignment: 1633513113.776543
Printing: 1633513113.777353
Printing: 1633513113.778350
Printing: 1633513113.779347
Printing: 1633513113.779347奇怪的是,它输出以下内容:
Assignment: 1633513088.000000
Printing: 1633513113.777353
Printing: 1633513113.778350
Printing: 1633513113.779347
Printing: 1633513113.779347第一行(Assignment: 1633513088.000000)的数字与预期的数字完全不匹配。秒数为off (不,两张照片之间没有25秒的停顿),毫秒数为0。我甚至不能完全确定从哪里开始。如果区别在于将值赋值给变量而不是直接打印它,那么我在赋值时做错了什么?可惜,输出是浮点型的,变量test也是浮点型的。
哪里出了问题,我如何修复它?
发布于 2021-10-06 10:02:32
正如Weather Vane所说的那样,使用浮动不足以满足我的精度要求。另一方面,一个替身正好提供了我需要的东西。我对我的代码做了以下更改:
我首先修改了返回计算,使其返回一个double而不是float
return time(NULL) + spec.tv_nsec / 1000000000.0;然后,我将函数返回类型分别更改为double
double getTime() { ... }我还将测试变量更改为double类型。
double test = getTime();最后,结果是:
Assignment: 1633514501.274064
Printing: 1633514501.275059
Printing: 1633514501.276059
Printing: 1633514501.277052
...https://stackoverflow.com/questions/69463415
复制相似问题