2017-05-07 24 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变量没有被使用。

相关问题