[英]How to find position of an element in array (C programming)
我有一個函數,要求用戶將 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;
}
最大值計算正確。 但是當我試圖找到最大值的位置時,我得到了一個瘋狂的數字。 我找到最大值位置的方式有什么問題?
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);
如果所有整數都大於零,以下只會找到最大值。 如果它們都是負整數,那么這里的最大值將為 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];
}
}
相反,您想用數組中的第一個元素初始化 maxVal,然后將所有其他元素與其進行比較(跳過 for 循環中的第一個元素,這樣您就不會將 maxVal 與其自身進行比較)。 這將在索引 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;
}
}
想象一下你有這個數組:{100 , 99 , 98 , 97 , 96 , 95 , 94 , 93 , 92 , 91 , 90}, 最大值是 100. 你的代碼試圖打印 array[maxValue] 所以 array[100] .
也許您不應該將值保存到 maxValue 中,而應該保存正確的位置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.