数组和循环:创建一个最重要的数字列表

时间:2013-10-13 21:35:06

标签: c++

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

我如何完成输出吃最多煎饼的人数,然后是最少量煎饼的人?

1 个答案:

答案 0 :(得分: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无论如何都是索引。
  3. 使用您的设置,计算吃最多或最少量煎饼的人数的最简单方法可能是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 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";
    }