数组和 For 循环:创建从大到小的数字列表

Arrays and For Loops: Creating a list of numbers Greatest to Least

本文关键字:从大到小 数字 列表 创建 For 循环 数组      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main() {
    int greatestToLeastPancakeAmount[10] = {};
    int greatestToLeastPersonNumber[10] = {};
    int pancakeAmount;
    int x;
    cout << "Pancake Glutton 1.0 nn"; //State program's title
    cout << "10 Different people ate pancakes for breakfast.. nn";
    x = 0;
    for(x=0;x<10;x++) {
        cout << "How many pancakes did person " << (x + 1) << " eat? > ";
        cin >> pancakeAmount;
        greatestToLeastPersonNumber[x] = (x + 1);
        greatestToLeastPancakeAmount[x] = pancakeAmount;
        /*while(pancakeAmount > greatestToLeastPancakeAmount[(x - 1)]) {
            int storeGreatestToLeastPancakeAmount = greatestToLeastPancakeAmount[(x-1)];
            int storeGreatestToLeastPersonNumber = greatestToLeastPersonNumber[(x-1)];
            greatestToLeastPancakeAmount[(x-1)] = pancakeAmount;
            greatestToLeastPersonNumber[(x-1)] = x;
            greatestToLeastPancakeAmount[x] = storeGreatestToLeastPancakeAmount;
            greatestToLeastPersonNumber[x] = storeGreatestToLeastPersonNumber;
        }*/
    }
    cout << "nn";
    for(x=0;x<10;x++) {
        cout << "Person " << greatestToLeastPersonNumber[x] << " ate " << greatestToLeastPancakeAmount[x] << " pancakes!n";
    }
    return 0;
}

我如何输出吃煎饼最多的人数,其次是煎饼量最少的人?

让我们从一般要求开始: 阅读后,您始终需要验证您是否成功阅读了您尝试阅读的任何内容,例如:

if (!(std::cin >> greatestToLeastPancakeAmount[x])) {
    std::cout << "failed to read number of pancakes (ignoring this line)n";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}

接下来,实际上不需要为人员存储任何标识符:

  1. 不需要。
  2. 存储的标识符始终i + 1 i无论如何都是索引。

使用您的设置,计算吃最多或最少煎饼的人数的最简单方法可能是std::sort()数组,然后在数组的开头和结尾计算相等计数的数量。然而,一种更简单的方法是,在std::map<int, int>中增加一个值,然后输出映射的第一个和最后一个元素:

std::map<int, int> count;
for (int i = 0; i != 10; ++i) {
    ++count[greatestToLeastPancakeAmount[i]];
}
if (count.empty()) { // won't happen until you start tracking the number of people entered
    std::cout << "nobody ate any pancaken";
}
else {
    std::cout << (--count.end())->second << " persons ate " << (--count.end())->first
              << " pancakesn";
    std::cout << count.begin()->second << " persons ate " << count.begin()->first
              << " pancakesn";
}