简体   繁体   中英

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.

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.

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.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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