首页 > 解决方案 > 在C中显示数组中的最大值

问题描述

当我运行它时,ageProgMax 显示为 29,而不是我想要的 60。我为分析师喝的最少数量的咖啡馆做了这个,它有效,但不知何故,这个没有。

int main()
{
    char poste[] ={'P', 'P', 'O', 'A', 'P', 'A', 'P', 'P'};
    int nbCafe[] ={5, 1, 3, 0, 5, 1, 0, 2};
    int age[] ={25, 19, 27, 22, 49, 24, 60, 29};
    int nbPers = sizeof(age) / sizeof(int);
    int i;
    int ageProgMax = 0;
    for (i = 0; i < nbPers; i++)
        if (poste[i] =='P' || age[i] > ageProgMax)
        {
      ageProgMax = age[i];
        }
    printf ("Max age of programmers : %d\n", ageProgMax);

    return 0;
}

有什么帮助吗?

谢谢

标签: carrays

解决方案


那是因为||你的情况。查看您设置的条件,即if (poste[i] =='P' || (age[i] > ageProgMax))。它说ageProgMax如果其中一个(age[i] > ageProgMax)poste[i] =='P'变为真,则存储新值。所以对于最后一个条目,29即使(age[i] > ageProgMax)是假的,也是真的,并导致 's被'sposte[i] =='P'覆盖。ageProgMax6029

您可以像这样更正您的程序。

int main()
{
    char poste[] ={'P', 'P', 'O', 'A', 'P', 'A', 'P', 'P'};
    int nbCafe[] ={5, 1, 3, 0, 5, 1, 0, 2};
    int age[]    ={25, 19, 27, 22, 49, 24, 60, 29};
    int nbPers = sizeof(age) / sizeof(int);
    int i;
    int ageProgMax = 0;

    for (i = 0; i < nbPers; i++)
    {
        if (poste[i] =='P' &&  (age[i] > ageProgMax))
        {
            ageProgMax = age[i];
        }
    }

    printf ("Max age of programmers : %d\n", ageProgMax);

    return 0;
}

推荐阅读