计数器和累加器不工作并导致程序崩溃。我究竟做错了什么?

标签 c if-statement while-loop counter accumulator

我已经摆弄这段代码几个小时了,尽管很简单,但我找不到它有什么问题。这是逻辑吗?或者问题与语法相关?

我希望程序要求用户输入一个数字,表示他们本月在比赛中单独跑了多少公里。 该程序将告诉他们在每场比赛中平均跑了多少距离。

话不多说,代码如下:

#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;  
} 

最佳答案

循环内

  scanf("%d", currentItem);

应该是

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

也就是说,main () 至少应该是 int main(void),以符合托管环境的标准。

关于计数器和累加器不工作并导致程序崩溃。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43834125/

相关文章:

c - 在 C 中访问字符指针字符串中的特定字符

c - printf 的格式说明符中的 'F' 是什么意思?

c - 64 位值的反转字节

PHP 如果继续执行,不管逻辑如何

c - do-while 循环没有结束

r - 对多个条件使用 if else 语句

php - 需要有关 PHP 循环中使用的特定 MySQL 查询的帮助

loops - 在 Mathematica : multiple outputs 中循环

c - 从C中的字符串中逐个字符地读取

c++ - 如何在循环外重新输入变量