2013-10-06 2 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 자리 표시자가 있지만 두 개의 매개 변수를 전달합니다.

관련 문제