1
#include <iostream>
using namespace std;

int main() {
    int greatestToLeastPancakeAmount[10] = {};
    int greatestToLeastPersonNumber[10] = {};
    int pancakeAmount;
    int x;
    cout << "Pancake Glutton 1.0 \n\n"; //State program's title
    cout << "10 Different people ate pancakes for breakfast.. \n\n";
    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 << "\n\n";
    for(x=0;x<10;x++) {
        cout << "Person " << greatestToLeastPersonNumber[x] << " ate " << greatestToLeastPancakeAmount[x] << " pancakes!\n";
    }
    return 0;
}

我如何完成输出吃煎饼最多的人数和吃最少煎饼的人数?

4

1 回答 1

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()是数组,然后计算数组开头和结尾处相等计数的数量。然而,一个更简单的方法是在 a 中增加一个值,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 pancake\n";
}
else {
    std::cout << (--count.end())->second << " persons ate " << (--count.end())->first
              << " pancakes\n";
    std::cout << count.begin()->second << " persons ate " << count.begin()->first
              << " pancakes\n";
}
于 2013-10-13T22:07:48.013 回答