现在,我正在学习C编程,我偶然发现了'Codeproject.com'上的倒计时代码,并决定运行它并分析它以便学习。但是,输出Countdown会在移动到下一个数字之前重复数千次。我需要帮助理解为什么会这样。代码如下所示:
#include <stdio.h>
#include <time.h>
int main()
{
unsigned int x_hours = 0;
unsigned int x_minutes = 0;
unsigned int x_seconds = 0;
unsigned int x_milliseconds = 0;
unsigned int totaltime = 0, count_down_time_in_secs = 0, time_left=0;
clock_t x_startTime, x_countTime;
count_down_time_in_secs = 10; // 1 min is 60
x_startTime = clock();
time_left = count_down_time_in_secs-x_seconds; //update timer
while (time_left>0)
{
x_countTime = clock();
x_milliseconds = x_countTime-x_startTime;
x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_hours*60);
x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60;
x_hours=x_minutes/60;
time_left = count_down_time_in_secs-x_seconds;
printf("\nyou have %d seconds left", time_left, count_down_time_in_secs);
}
printf("\n\n\nTime's out\n\n\n");
return 0;
}
答案 0 :(得分:1)
计算机速度很快,因此循环将每秒执行多次。您需要存储上一次,将其与当前时间进行比较,只有在更改时才打印出来。
此外,您的printf()
来电只有一个%d
占位符,但您要传递两个参数。
答案 1 :(得分:0)
只需添加一行就可以在循环内打印出x_milliseconds,这将显而易见。即你每秒执行你的循环数千次。