【问题标题】:Assigning function output to variable in C gives different output than printing the output directly将函数输出分配给 C 中的变量会产生与直接打印输出不同的输出
【发布时间】:2021-11-26 11:57:04
【问题描述】:

在我不断尝试学习 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) 的数字与预期的完全不匹配。秒数已关闭(不,两次打印之间没有 25 秒的暂停),毫秒数为 0。我什至不完全确定从哪里开始。如果区别在于将值分配给变量而不是直接打印它,那么我在分配时做错了什么?唉,输出是浮点数,变量test也是浮点数。

出了什么问题,我该如何解决?

【问题讨论】:

  • float 类型没有足够的精度,通常约为 7 个十进制数字。请使用double,大约有 16 个。切勿使用float,除非您有特定原因不能使用double
  • Xiddoc,注意clock_gettime() 不是标准的 C 函数。
  • 不方便调用time()clock_gettime()。最好使用timespec_get()等1个函数,

标签: c function


【解决方案1】:

正如 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
...

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 2012-06-13
    • 2017-09-28
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多