2013-10-13 81 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"; 
} 
相關問題