简体   繁体   English

如何在数组中找到元素的位置(C 编程)

[英]How to find position of an element in array (C programming)

I have a function that asks the user to input 10 integers into an array then finds the max value of the array.我有一个函数,要求用户将 10 个整数输入一个数组,然后找到数组的最大值。

int largestPos(int array[], int size, int index) {

int k, maxVal = 0;

printf("Enter a starting index: ");
scanf("%d", &index);

for (k = index; k < size; k++){
    if (maxVal < array[k]){
        maxVal = array[k];
    }
}
printf("The maximum value is %d at position %d \n", maxVal, array[maxVal]);

return 0;

} }

The max value calculates correct.最大值计算正确。 But when I try to find the position of the max value, I get a crazy number.但是当我试图找到最大值的位置时,我得到了一个疯狂的数字。 What is wrong with the way I am finding the position of the max value?我找到最大值位置的方式有什么问题?

int maxPos=0;    

for (k = index; k < size; k++){
        if (maxVal < array[k]){
            maxVal = array[k];
            maxPos = k;
        }
    }    

    printf("The maximum value is %d at position   %d \n", 
maxVal, maxPos);

The following will only find the max value if all the integers are greater than zero.如果所有整数都大于零,以下只会找到最大值。 If they're all negative integers then the max value here would be 0.如果它们都是负整数,那么这里的最大值将为 0。

int array[5] = {-234, -133, -581, -8, -41};

int maxVal = 0;

for(i = 0; i < size; ++i) {
    if(array[i] > maxVal) {
        maxVal = array[i];
    }
}

Instead you want to initialize maxVal with the first element inside the array, then compare every other element to it (skipping the first element in the for loop so you're not comparing maxVal to itself).相反,您想用数组中的第一个元素初始化 maxVal,然后将所有其他元素与其进行比较(跳过 for 循环中的第一个元素,这样您就不会将 maxVal 与其自身进行比较)。 This will give the max value of -8 at index 3.这将在索引 3 处给出 -8 的最大值。

int array[5] = {-234, -133, -581, -8, -41};

// initialize maxVal to first element inside the array
int maxVal = array[0];
int pos = 0;

for(i = 1; i < size; ++i) {
    if(array[i] > maxVal) {
        maxVal = array[i];
        // Find the index of the max value
        pos = i;
    }
}

Imagine you have this array : {100 , 99 , 98 , 97 , 96 , 95 , 94 , 93 , 92 , 91 , 90}, the max value is 100. Your code tries to print array[maxValue] so array[100].想象一下你有这个数组:{100 , 99 , 98 , 97 , 96 , 95 , 94 , 93 , 92 , 91 , 90}, 最大值是 100. 你的代码试图打印 array[maxValue] 所以 array[100] .

Maybe you should not save the value into maxValue but rather the position to get something correct也许您不应该将值保存到 maxValue 中,而应该保存正确的位置

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

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