我正在编写一个 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;
}
最佳答案
您的问题在于:
scanf("%d\n", num);
scanf
需要变量的内存地址,其中应该放置读取的值。这是使用运算符 &
完成的。您的代码应该是:
scanf("%d\n", &num);
关于c - 如何修复段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655710/