我正在嘗試編寫一個程序,該程序可以使用maxterm函數查找數組的最大值。嘗試使用C查找數組中的最大項C
基本上你會告訴程序你想在數組中放入多少個數字,放在每個數字中,它會告訴你最大的數字。
該程序適用於數組大小爲4或更小的數組,但只要數組變長超過4,返回的maxterm就不正確:它始終是一個甚至不是數組的一部分的大數。
例如:
Please enter the number of data values: 4
enter value 1: 1
enter value 2: 3
enter value 3: 4
enter value 4: 1
the maximum term is 4
但是:
Please enter the number of data values: 5
enter value 1: 1
enter value 2: 3
enter value 3: 8
enter value 4: 4
enter value 5: 2
the maximum term is 32767
這裏是我的代碼:
#include <stdio.h>
int maxterm(int *numbers, int *size) {
int index = 0;
int max = numbers[0];
for (index = 0 ; index < *size ; index++) {
if (max < numbers[index+1]) {
max = numbers[index+1];
}
}
return max;
}
int main(int argc, const char * argv[]) {
int num, index;
printf(" Please enter the number of data values: ");
scanf("%d", &num); //user enters in the length of the number list
int array[num];
for (index = 0 ; index < num ; index++) {
printf("Please enter in value %i: ", (index + 1));
scanf("%i", &array[index]); //list is created number by number
}
int maxi = maxterm(array, &num); //the highest number in the list is then determined using the maxterm function.
printf("the maximum term is %i", maxi);
return 0;
}
哪裏是我的錯誤?