简体   繁体   English

尝试使用C查找数组中的最大项

[英]Trying to find the maximum term in an array using C

I am trying to write a program that can find the maximum of an array by using a maxterm function. 我试图编写一个程序,可以通过使用maxterm函数找到最大的数组。

Basically you tell the program how many numbers you want to put in the array, put in each number, and it tells you the largest number. 基本上你告诉程序你要在数组中放入多少个数字,放入每个数字,它会告诉你最大的数字。

The program works fine with arrays of size 4 or smaller but as soon as the arrays get longer than 4 the maxterm that is returned is incorrect: it's always a large number that wasn't even part of the array. 该程序适用于大小为4或更小的数组,但只要数组长度超过4,返回的最大值就不正确:它总是一个大数,甚至不是数组的一部分。

For example: 例如:

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

But: 但:

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

Here is my code: 这是我的代码:

#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;
}

Where is my error? 我的错误在哪里?

You are going out of bounds here: 你在这里出界:

for (index = 0 ; index < *size ; index++)   {
    if (max < numbers[index+1])   {
        max = numbers[index+1];
    } 
}

Instead iterate normally, except start with the second element. 而是正常迭代,除了从第二个元素开始。

You are accessing array out of bound so you are seeing this issue. 您正在访问数组越界,所以你看到这个问题。 Pass by value looks good for this API. 通过值看起来很适合此API。

 int maxterm(int *numbers, int size)     {

    int index = 0;
    int max = numbers[0];



    for (index = 0 ; index < size ; index++)   {
        if (max < numbers[index])   {
            max = numbers[index];
        }
    }
    return max;

    }

The call should be: 电话应该是:

int maxi = maxterm(array, num);

You code is perfect. 你的代码是完美的。 Just replace it i+1 with i in the max function 在max函数中用i替换i + 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM