#include <iostream>
using namespace std;
int main()
{
int t;
int temp[99];
for (int i = 0; i < 10; i++) {
cin >> temp[i];
}
for (int a = 0; a < 11; a++) {
for (int b = 0; b < 11; b++) {
if (temp[a] > temp[b]) {
t = temp[a];
}
}
}
for (int a = 1; a < 11; a++) {
if (temp[a] = t) {
cout << "Person " << temp[a] << " ate the most pancakes\n" ;
}
}
system("pause>nul");
return 0;
}
所以我在 cplusplus.com 上做这个名为 pancake glutton 的练习题。通过这段代码,我只是想确定谁吃的煎饼最多,但每次我完成这个程序时,我都会得到很多数字和一个重复最后一个 forloop 5 次。我究竟做错了什么 ?这里是。 “煎饼馋嘴 要求: 变量、数据类型和数值运算符 基本输入/输出 逻辑(if 语句、switch 语句) 循环(for,while,do-while) 数组
编写一个程序,要求用户输入 10 个不同的人(第 1 人、第 2 人、...、第 10 人)早餐吃的煎饼的数量 输入数据后,程序必须分析数据并输出哪个人早餐吃煎饼最多。
★ 修改程序,让它也输出哪个人早餐吃煎饼的数量最少。
★★★★ 修改程序,输出一个列表,按照所有 10 个人吃的煎饼的数量排序。 即
Person 4: ate 10 pancakes
Person 3: ate 7 pancakes
Person 8: ate 4 pancakes
...
Person 5: ate 0 pancakes"
最佳答案
您的代码包含多个错误。 1).变量 t 未初始化。 2).您只输入了 10 个元素。这意味着有效的索引是 0 - 9。但是你尝试访问 11 个元素而不是 10 个。所以循环是这样的
for(int a = 0;a<11;a++)
不正确。
3) 这些循环没有任何意义。
for(int a = 0;a<11;a++)
{
for(int b = 0;b<11;b++)
{
if(temp[a]>temp[b])
{
t = temp[a];
}
}
}
4) 这里使用赋值运算符代替比较运算符
if (temp[a] = t)
5) 你应该包含标题 <cstdlib>
因为您使用了 header 中声明的函数系统。
据我了解,您所需要的只是编写代码来查找数组元素中的最大值。
要查找最大元素的索引,您可以使用以下代码。
int theBiggest = 0;
for ( int i = 1; i < 10; i++ )
{
if ( temp[theBiggest] < temp[i] ) theBiggest = i;
}
cout << "Person " << theBiggest << " ate the most pancakes equal to " << temp[theBiggest] << endl ;
关于c++ - Pancake Glutton 寻找数组中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20836598/