2013-10-06 44 views
0

現在,我正在學習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; 
} 

回答

0

只需添加一行以在您的循環內打印出x_milliseconds,它就會變得很明顯發生了什麼。即您每秒執行數千次循環。

1

計算機速度很快,所以循環會每秒執行多次。您需要存儲之前的時間,將其與當前時間進行比較,並且只有在更改時纔打印。

另外你的printf()調用只有一個%d佔位符,但是你傳遞了兩個參數給它。