现在,我正在学习 C 编程,我在“Codeproject.com”上偶然发现了一个倒计时代码,并决定运行它并分析它来学习。但是,输出倒计时会在移动到下一个之前重复每个数字数千次。请帮助我理解这是为什么。代码如下所示:
#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;
}
最佳答案
计算机速度很快,所以循环每秒会执行很多次。您需要存储以前的时间,将其与当前时间进行比较,只有在发生变化时才打印。
此外,您的 printf()
调用只有一个 %d
占位符,但您向它传递了两个参数。
关于c++ - 计数器一直重复请提供答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19215280/