2013-10-13 34 views
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; 
} 

我该如何完成输出吃煎饼的人最少的人吃的人数?数组和循环:创建一个数字列表最大到最小

+0

有一个'的std :: minmax'算法。 – chris

+0

这就像告诉某人不知道如何钓鱼使用钓鱼竿,并期望他们钓到鱼一样。 – user2877063

+0

那么,参考页面,如[这一个](http://en.cppreference.com/w/cpp/algorithm/minmax)通常包含使用示例以及参数等信息。 – chris

回答

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 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"; 
} 
相关问题