我编写的代码可以让你看到哪个人吃得最多,最少吃。但是,我的代码无法找到最少吃的人。我能够找到谁吃得最多,我尝试使用该代码的反面来找到谁吃得最少。这是代码:
#include <iostream>
using namespace std;
int main()
{
int people[10] = { 1,2,3,4,5,6,7,8,9,10 };
int pancakes[10];
int m = 0; // most pancakes eaten
int l = 1; // least pancakes eaten
int mp = 0; // most people
int lp = 1; // least people
for (int x = 0; x < 10; x++)
{
cout << people[x] << " ate: ";
cin >> pancakes[x];
}
for (int x = 0; x < 10; x++)
{
if (pancakes[x] > m)
{
m = pancakes[x];
mp = people[x];
}
else if (pancakes[x] <= l)
{
l = pancakes[x];
lp = people[x];
}
}
cout << endl;
cout << mp << " person ate most: " << m << " pancakes\n";
cout << lp << " person ate least: " << l << " pancakes\n";
return 0;
}
附:我可以使用这些:
要么将l
初始化为大数,要么更好地使l
成为数组中的某些值,如:l = pancakes[0]
。在第一行下方添加该行,如下所示:
for(int x = 0; x < 10; x++)
{
cout << people[x] << " ate: ";
cin >> pancakes[x];
}
m = pancakes[0];
l = pancakes[0];
...
m
和l
应该是来自pancakes
数组的实际值,而不是一些随机值。
您的代码无效,因为您将l
设置为1
,并且只有当有人吃了少于1个煎饼时,才会执行最后一个if
语句中的代码。