c - 如何修复段错误?

标签 c loops gcc segmentation-fault sentinel

我正在编写一个 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/

相关文章:

objective-c - 为什么结构和基本类型不需要指针?

javascript - 如何迭代 JSON 结构?

编译时出现 C++ 错误

c - 将数组映射到结构时的顺序相反

c - "small"是c 中的关键字吗?

带有 int 迭代器的 Python 循环

javascript - 如何将查询结果推送到node.js中的数组变量?

c++ - constexpr 和使用重新解释强制转换的静态 const void 指针的初始化,哪个编译器是正确的?

使用下一个代码语句的 C 宏或 GCC 指令

c - 如何正确使用多维数组中的指针?