c - 在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;
}
有什么帮助吗?
谢谢
解决方案
那是因为||
你的情况。查看您设置的条件,即if (poste[i] =='P' || (age[i] > ageProgMax))
。它说ageProgMax
如果其中一个(age[i] > ageProgMax)
或poste[i] =='P'
变为真,则存储新值。所以对于最后一个条目,29
即使(age[i] > ageProgMax)
是假的,也是真的,并导致 's被'sposte[i] =='P'
覆盖。ageProgMax
60
29
您可以像这样更正您的程序。
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;
}
推荐阅读
- c# - 如果按钮位于父面板中,则模板中单选按钮的双向绑定会出错
- html - 锚标签上的下载属性不适用于边缘中的相对路径
- dart - 我应该使用构造函数或方法来实现 Json 到 List
- arrays - 在 Swift 中拆分行而不省略空行
- matlab - 如何在 MATLAB 中替换标志之间的字符
- javascript - 在 Safari 中拖动时数据工具提示不起作用
- mysql - SQL [不适用];嵌套异常是 org.hibernate.exception.SQLGrammarException: could not extract ResultSet
- python - 展平 Python Dict 并且仅在不唯一时更改键
- azure-cosmosdb - Gremlin CosmosDB 尝试从节点列表中查询节点列表并将两者都返回
- vue.js - 无法使用 vue 和 express 使用 axios POST