我正在完成一些初学者练习,并得到了这个问题,“Pancake Glutton”。
“编写一个程序,要求用户输入 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"
我设法输出了最多和最少吃的煎饼,但我卡在了最后一点!
我可以按降序输出吃的煎饼数量,即 6、5、4、3、2 等。但我正在努力弄清楚如何将每个煎饼数量分配给吃它们的用户?
我曾尝试使用与其他两个 for 循环相同的技术,但我知道这是不正确的,因为此方法不会将用户分配给他们吃的煎饼数量。
我觉得我在这里遗漏了一些非常简单的东西!感谢您的帮助!
#include <iostream>
using namespace std;
int main()
{
cout << "how many pancakes did you eat for breakfast?" << endl;
int person1, person2, person3, person4, person5;
cout << "Person 1: ";
cin >> person1;
cout << "Person 2: ";
cin >> person2;
cout << "Person 3: ";
cin >> person3;
cout << "Person 4: ";
cin >> person4;
cout << "Person 5: ";
cin >> person5;
int array[5] = {person1, person2, person3, person4, person5};
int temp = 0;
int res = -1;
for (int i = 0; i < 5; i++)
{
if (array[i] > temp)
{
temp = array[i];
res = i;
}
}
cout << "The most pancakes eaten was " << temp << " by Person " << (res+1) << endl;
int smallest = array[0];
int res2 = 0;
for (int i = 1; i < 5; i++)
{
if (array[i] < smallest)
{
smallest = array[i];
res2 = i;
}
}
cout << "The least pancakes eaten was " << smallest << " by Person " << (res2+1) << endl;
int temp3 = 0;
int res3 = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (array[i] > array[j])
{
temp3 = array[i];
array[i] = array[j];
array[j] = temp3;
res3 = i;
}
}
}
for (int i = 0; i < 5; i++)
{
cout << "Person " << res3 << " ate " << array[i] << " pancakes" << endl;
}
}
最佳答案
你的问题是你失去了索引和数字之间的关系。看起来,您需要使用一个包含此人的 ID 和他吃的煎饼数量的数据结构。
struct PancakeEater {
int numberOfPancakes;
int personId;
};
如果我是你,我会放弃原始数组,并尝试使用 std::vector<PancakeEater>
并使用类似 std::sort
的算法.这是描述in another question .
关于c++ - 如何输出哪个用户输入了每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32330953/