首页 > 解决方案 > 使用时钟()输出持续时间,但输出相乘

问题描述

所以,我想显示程序以秒为单位打开的持续时间,但它显示的是多秒而不是一个字符。前任。1 到 11111 这是代码:

int main() {
   clock_t start;
   double duration;
   int seconds;

   start = clock();
   while (true) {
      if ((clock() - start) % CLOCKS_PER_SEC == 0) {
        cout << (clock() - start) / (double)CLOCKS_PER_SEC;
      }
   }
}

输出 :

01111111111111111111111222222222233333333333334444444445555555556666666666666667777777777777

帮我解决这个问题

标签: c++clock

解决方案


你的if支票完全错了。想象一下,如果您的while循环运行两次并且没有变化,clock()因为它循环非常快。它要么输出两次,要么不输出任何时间。这不可能是对的。

正确的检查是查看自上次生成输出以来是否已过去至少一秒钟。

 clock_t last_output;
 start = last_output = clock();
 while (true) {
      if (clock() > (last_output + CLOCKS_PER_SEC)){
          last_output += CLOCKS_PER_SEC;
          cout << (clock() - start) / (double)CLOCKS_PER_SEC;
    }
 }

这是完整的代码:

#include <time.h>
#include <iostream>

int main()
{
    clock_t start, last_output;

    start = last_output = clock();
    while (true)
    {
        if (clock() > (last_output + CLOCKS_PER_SEC))
        {
            last_output += CLOCKS_PER_SEC;
            std::cout << (clock() - start) / (double)CLOCKS_PER_SEC << std::endl;
        }
     }
}

推荐阅读