2017-05-07 77 views
-1

我一直在這個代碼附近玩了幾個小時,儘管很簡單,但我找不到它有什麼問題。這是邏輯嗎?或者問題是與語法相關的問題?計數器和累加器無法正常工作,導致程序崩潰。我究竟做錯了什麼?

我希望程序要求用戶輸入一個數字,指出他們本月在比賽中個人跑完了多少公里。 該方案將平均告訴他們每場比賽他們跑了多少。

事不宜遲,下面的代碼:

#include <stdio.h> 

main() 
{ 
    int STOP_VALUE = 8 ; /* you pick this number - outside the valid data set */ 

    int avg; 
    int currentItem; 
    float runningTotal = 0 ; 
    int counterOfItems = 0 ; 

    printf("Enter first item or 8 to stop: "); 

    scanf("%d", &currentItem); 

    while (currentItem != 8) { 

      runningTotal += currentItem; 

     ++counterOfItems; 

     printf("Enter next item or 8 to stop: "); 
     scanf("%d", currentItem);  

} 

    /* protect against division by 0 */ 
    if (counterOfItems != 0) 
    { 

      avg = runningTotal/counterOfItems ;} 
    else { 



    printf("On average, you've run %f per race and you've participated in %f running events. Bye! \n", runningTotal, counterOfItems); 
    } 

    return 0; 
} 
+0

預期產量是多少?你會得到什麼? – DyZ

回答

1

在循環中

scanf("%d", currentItem); 

應該

scanf("%d", &currentItem); 
      ^^ 

也就是說,main()應該int main(void),至少,以符合託管環境的標準。

1

你的avg變量是一個int,它將被四捨五入,你可能會得到一些奇怪的結果。

其實是一個更新,你的avg變量沒有被使用。

相關問題