计数器和累加器不工作并导致程序崩溃。我究竟做错了什么?
Counters and accumulators not working and making the program crash. What am I doing wrong?
我已经研究这段代码几个小时了,虽然很简单,但我找不到它有什么问题。这是逻辑吗?或者问题与语法相关?
我希望程序要求用户输入一个数字,表明他们 运行 在本月的比赛中分别 运行 跑了多少公里。
该程序会告诉他们在每场比赛中 运行 的平均成绩。
事不宜迟,代码如下:
#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", ¤tItem);
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", ¤tItem);
^^
也就是说,main ()
至少应该 int main(void)
,以符合托管环境的标准。
您的 avg 变量是一个 int,它将被四舍五入,您最终可能会得到一些奇怪的结果。
实际上是一个更新,你的 avg 变量没有被使用。
我已经研究这段代码几个小时了,虽然很简单,但我找不到它有什么问题。这是逻辑吗?或者问题与语法相关?
我希望程序要求用户输入一个数字,表明他们 运行 在本月的比赛中分别 运行 跑了多少公里。 该程序会告诉他们在每场比赛中 运行 的平均成绩。
事不宜迟,代码如下:
#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", ¤tItem);
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", ¤tItem);
^^
也就是说,main ()
至少应该 int main(void)
,以符合托管环境的标准。
您的 avg 变量是一个 int,它将被四舍五入,您最终可能会得到一些奇怪的结果。
实际上是一个更新,你的 avg 变量没有被使用。