繁体   English   中英

C程序查找数组中最大元素的每个索引(在不同位置有多个具有相同最大值的元素)

[英]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.

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