gpt4 book ai didi

c - 在 C 中搜索整数数组中的最大数字

转载 作者:行者123 更新时间:2023-12-02 22:27:12 26 4
gpt4 key购买 nike

这延续了我之前的 question .

我有一个数组,想找出其中最大的数字。但是我不能排序,因为数字的索引非常重要,所以不能移动。最后,我的问题的输出应该是“最大的数字在索引 1 和 4 中,数字为 8。这是数组:

int anonarray[5] = {3,8,7,5,8};

最佳答案

enum { MAX_ENTRIES = 5 };
int anonarray[MAX_ENTRIES] = { 3, 8, 7, 5, 8 };
int maxval = anonarray[0];
int maxidx[MAX_ENTRIES] = { 0, 0, 0, 0, 0 };
int maxnum = 1;

for (int i = 1; i < MAX_ENTRIES; i++)
{
if (maxval < anonarray[i])
{
/* New largest value - one entry in list */
maxval = anonarray[i];
maxnum = 1;
maxidx[0] = i;
}
else if (maxval == anonarray[i])
{
/* Another occurrence of current largest value - add entry to list */
maxidx[maxnum++] = i;
}
}

printf("The biggest number is in %s", ((maxnum > 1) ? "indices" : "index"));
const char *pad = " ";
for (int i = 0; i < maxnum - 1; i++)
{
printf("%s%d", pad, maxidx[i]);
pad = ", ";
}
printf(" %s%d, with value %d.\n", ((maxnum > 1) ? "and " : ""),
maxidx[maxnum-1], maxval);

请注意,将特定于英语的格式国际化并不一定容易!

关于c - 在 C 中搜索整数数组中的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791180/

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