在 C++ 中寻找吃得最少的人
Finding person who ate least in C++
我编写了代码,可以让您看到哪个人吃得最多和最少。但是,我的代码无法找到谁吃得最少。我能够找出谁吃得最多,并尝试使用与该代码相反的代码来找出谁吃得最少。这是代码:
#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;
}
P.S。我只能使用这些:
- 变量、数据类型和数值运算符
- 基本input/output
- 逻辑(if 语句、switch 语句)
- 循环(for、while、do-while)
- 数组
要么将 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
语句中的代码。
我编写了代码,可以让您看到哪个人吃得最多和最少。但是,我的代码无法找到谁吃得最少。我能够找出谁吃得最多,并尝试使用与该代码相反的代码来找出谁吃得最少。这是代码:
#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;
}
P.S。我只能使用这些:
- 变量、数据类型和数值运算符
- 基本input/output
- 逻辑(if 语句、switch 语句)
- 循环(for、while、do-while)
- 数组
要么将 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
语句中的代码。