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

标签 c search

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

相关文章:

java - 单击搜索小部件时 Intent 进行下一个 Activity

ruby-on-rails - 用太阳黑子重新索引一个特定的记录

c - thrd_join 的返回值与其 res 参数的区别?

将 "normal"矩形转换为一组 GLes vector ?

c - 是否有任何工具可以确定程序在运行时进入哪些功能?

c - 在 C 语言中向文件追加位

iOS - NSInternalInconsistencyException(表搜索)

php - MYSQL LIKE 对于不同的语言有不同的行为,所有表都是utf8

c++ - 在结构中搜索具有相似属性的数据

c - 如何制作程序的流程?