我正在编写一个 C 程序,该程序应该添加每个数字,直到它达到一个标记值。然后将它们平均在一起。
我不确定问题出在哪里,但我认为 num 可能从未真正改变过。任何帮助表示赞赏。
#include <stdio.h>
int sentinal = 9999;
int iterations = 0;
int total = 0;
int average;
int num;
int main(void){
do{
printf("Enter a number to add:\n");
scanf("%d\n", num);
total = total + num;
iterations++;
}while (num != sentinal);
average = total/iterations;
printf("%d\n", average;
return 0;
}
运行版本
#include <stdio.h>
int main(){
int sentinel = 9999;
int iterations = 0;
int total = 0;
float average;
int num;
while(1){
printf("\nEnter a number to add: ");
scanf("%d", &num);
if (num == sentinel){
break;
}else{
total = total + num;
iterations++;}
}
average = (float) total/iterations;
printf("%f\n", average;
return 0;
}