gpt4 book ai didi

c - 需要显示多个数组中前3个最大的数字

转载 作者:行者123 更新时间:2023-11-30 20:02:58 26 4
gpt4 key购买 nike

不知道如何找到前 3 个最大数字以及如何仅显示前 3 个最大数字

float feb10[] = { 25.0, 24.8, 24.8, 24.7, 25.1, 25.4, 25.1, 25.1, 25.0, 24.5, 24.3, 24.1 };

float feb11[] = { 23.8, 23.3, 22.9, 22.8, 22.9, 23.3, 23.1, 23.7, 23.0, 22.6, 22.9, 22.8 };

float feb12[] = { 22.8, 22.6, 22.8, 22.8, 24.2, 25.3, 24.8, 24.2, 24.2, 24.1, 24.7, 24.8 };

float feb13[] = { 24.9, 25.0, 24.9, 25.1, 25.4, 25.7, 25.9, 25.4, 25.1, 24.9, 25.2, 25.0 };

float feb14[] = { 25.0, 24.7, 24.6, 24.5, 25.3, 25.1, 25.2, 25.1, 24.9, 24.1, 24.1, 24.2 };

结果应该是

1st highest is 25.9

2nd highest is 25.7

joint 3rd highest is 25.4

最佳答案

我们初学者应该互相帮助。:)

完成该任务的一个简单方法是声明数组的数组。

还为三个最大元素声明一个数组。然后使用插入排序将当前最大的元素包含到最大元素数组中。

这是一个演示程序。

#include <stdio.h>

int main(void)
{
double feb10[] = { 25.0, 24.8, 24.8, 24.7, 25.1, 25.4, 25.1, 25.1, 25.0, 24.5, 24.3, 24.1 };
double feb11[] = { 23.8, 23.3, 22.9, 22.8, 22.9, 23.3, 23.1, 23.7, 23.0, 22.6, 22.9, 22.8 };
double feb12[] = { 22.8, 22.6, 22.8, 22.8, 24.2, 25.3, 24.8, 24.2, 24.2, 24.1, 24.7, 24.8 };
double feb13[] = { 24.9, 25.0, 24.9, 25.1, 25.4, 25.7, 25.9, 25.4, 25.1, 24.9, 25.2, 25.0 };
double feb14[] = { 25.0, 24.7, 24.6, 24.5, 25.3, 25.1, 25.2, 25.1, 24.9, 24.1, 24.1, 24.2 };

double * a[] = { feb10, feb11, feb12, feb13, feb14 };
const size_t M = sizeof( a ) / sizeof( *a );
const size_t N = sizeof( feb10 ) / sizeof( *feb10 );

enum { LARGEST_SIZE = 3 };
double max_values[LARGEST_SIZE] = { a[0][0] };
size_t filled = 1;

for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
size_t pos = 0;
while ( pos < filled && !( max_values[pos] < a[i][j] ) ) ++pos;

if ( pos == filled )
{
// If the array of largest elements is not filled then
// just append the array with the current largest element.
if ( filled != LARGEST_SIZE )
{
max_values[filled++] = a[i][j];
}
}
else
{
// Here is used the insertion sort
for ( size_t k = LARGEST_SIZE; --k != pos; ) max_values[k] = max_values[k-1];
max_values[pos] = a[i][j];
}
}
}

for ( size_t i = 0; i < LARGEST_SIZE; i++ ) printf( "%.1f ", max_values[i] );
putchar( '\n' );

return 0;
}

它的输出是

25.9 25.7 25.4

看来您正在期待这个结果。:)

关于c - 需要显示多个数组中前3个最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57188743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com