这延续了我之前的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/