【发布时间】:2016-12-17 23:39:49
【问题描述】:
这是一个简单的程序,它找到 10 数组的最小和最大元素。我不确定为什么会出现分段错误(核心转储)错误。
#include <stdio.h>
int main(void) {
int i, j, min, array[10], max, n;
//This loop get user input for the elements of the array
for(i = 0; i < 10; i++) {
printf("Enter element number %d:", i);
scanf("%d", &n);
array[i] = n;
}
min = array[0];
max = array[0];
//This loop finds the smallest element of the array
for(j = 0; j < 10; j++) {
if(min > array[j]) {
min = array[j];
}
}
//This loop finds the largest element of the array
for(j = 9; j >= 0; j++) {
if(max < array[j]) {
max = array[j];
}
}
printf("smallest value is: %d", min);
printf("largest value is: %d", max);
return 0;
}
【问题讨论】:
-
答案告诉你是你的错误,所以我会暗示一些别的东西:试着找到一种方法,你只使用线性时间来找到最小值和最大值,而不是二次时间。跨度>
-
@MeikVtune 这里没有二次元...你的意思是一次遍历而不是两次遍历?
-
@Quentin 是的 :)
标签: c segmentation-fault