【发布时间】:2013-09-29 23:44:02
【问题描述】:
我正在尝试让 C 程序使用 clock_t 中的“秒”作为 for 循环计数器。这怎么可能?下面是我的编码,它不起作用,
#include<stdio.h>
#include <time.h>
int main()
{
clock_t begin, end;
double time_spent;
begin = clock();
time_spent = (double)begin / CLOCKS_PER_SEC;
for(time_spent=0.0; time_spent<62000.0; time_spent++)
{
printf("hello \n");
if(time_spent==5.0)
break;
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf(" %lf\n", time_spent);
}
【问题讨论】:
-
您使用
(double)begin...分配了time_spent,然后在您的以下for语句中覆盖了它。由于浮点值的内部舍入错误,检查time_spent == 5.0也不是一个好主意。它可能永远不会准确命中5.0。 -
您是想循环(尽可能多地)直到经过一定的时间,还是以特定的间隔循环一定的时间?