寻找至少使用C ++的人

问题描述 投票:0回答:1

我编写的代码可以让你看到哪个人吃得最多,最少吃。但是,我的代码无法找到最少吃的人。我能够找到谁吃得最多,我尝试使用该代码的反面来找到谁吃得最少。这是代码:

#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;
}

附:我可以使用这些:

  • 变量,数据类型和数字运算符
  • 基本输入/输出
  • 逻辑(if语句,switch语句)
  • 循环(for,while,do-while)
  • 阵列
c++ codeblocks
1个回答
2
投票

要么将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];
...

ml应该是来自pancakes数组的实际值,而不是一些随机值。

您的代码无效,因为您将l设置为1,并且只有当有人吃了少于1个煎饼时,才会执行最后一个if语句中的代码。

© www.soinside.com 2019 - 2024. All rights reserved.