![](/img/trans.png)
[英]Find maximum value and indices of a maximum without using max built in functions
[英]C program to find each of the indices of the maximum element in an array (there are multiple elements with the same max value in different positions)
我想要什么:假設有一個一定大小的數組。 首先,我想找到數組中的最大元素,如果有多個元素具有相同的最大值,那么我想存儲最大元素的每個索引而不改變數組中元素的順序.
示例:假設有兩個班級:A 班和 B 班。在一次考試中,A 班的每個學生的得分都不同,因此我們可以很容易地找到該考試的最高分和誰得分。 但是,在同一次考試中,B班的兩名學生得分最高。 現在,我們必須確定這兩個學生(例如,借助他們的卷號)和他們的得分。 我不知道該怎么做!
我所知道的:我知道如何編寫一個 C 程序來找到具有索引值的數組中的最大值。 但是,如果在數組中的不同位置有多個具有相同最大值的元素,那么我想我需要一個新數組來存儲最大元素的索引。 一旦我實現了這一點,我可以借助任何存儲的索引輕松找到最大值。
我的嘗試:
#include<stdio.h>
int main(void)
{
size_t arr[5] = {2,8,10,7,10};
size_t i,j,max = arr[0];
size_t indices[5]={0};
for(j = 0;j < 5; ++j)
{
for(i = 0;i < 5; ++i)
{
if(arr[i] >= max)
indices[j] = i;
}
printf("Max Value: %zu ----> Position: %zu\n",arr[indices[j]],indices[j]+1);
}
return 0;
}
它生成的輸出:
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
(我知道它不會起作用,但它也沒有起作用。索引 3 在這個過程中迷路了!)
所需的輸出應如下所示:
Max Value: 10 ----> Position: 3
Max Value: 10 ----> Position: 5
請建議我如何編寫可以執行所需任務的 C 程序。
首先,您永遠不會覆蓋max
變量,因此您將數組上的每個值與arr[0]
進行比較,在本例中為 2。
一旦解決了這個問題,您就有多種解決方案來解決您的問題。
最簡單的一個(雖然不是最有效的):迭代一次以獲得最大值,然后再次迭代以獲得該值的每次出現。
替代方案:只迭代一次。 如果arr[i] < max
什么都不做。 如果arr[i] == max
存儲它的索引。 如果arr[i] > max
update max
,清除索引列表並存儲當前索引。
此外,在存儲索引時要小心,因為0
表示數組的第一個元素,不應用作“空”值。
首先循環查找最大元素,然后循環查找值等於該最大值的位置。
#include<stdio.h>
int main(void)
{
size_t arr[5] = {2,8,10,7,10};
size_t max = arr[0];
size_t indices[5]={0};
for(size_t i = 0; i < 5; ++i) if(arr[i] > max) max = arr[i];
size_t top = 0; // top contains count of elements with val = max
for(size_t j = 0; j < 5; ++j)
{
if(arr[j]==max){
indices[top] = j;
printf("Max Value: %zu ----> Position: %zu\n",arr[indices[top]],indices[top]+1);
top++;
}
}
return 0;
}
#include <stdio.h>
詮釋主要(){
int j, i, max, element, maxElement = 0;
int arr[5] = {2,8,10,7,10};
for(i = 0;i < 5; i++){ // loop to find highest index
element = arr[i];
if(element > max)max = element;} // highest index stored in 'max'
for(j = 0; j < 5; j++){ // second loop to find instances where 'max' is matched
maxElement = arr[j];
if(arr[j] == max)
printf("arr[%d] has max of %d\n",j,max);
}
返回0;
}
輸出:arr[2] 的最大值為 10
arr[4] 的最大值為 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.