2014-09-10 109 views
1

因此,我編寫了一個程序,要求用戶輸入一個人(1-10)早餐煎餅的數量。該計劃必須分析輸入並確定哪個人吃了最多的煎餅。此外,程序必須按照所有10人所吃的煎餅數量的順序輸出一個列表。到目前爲止,我已經編寫了代碼來獲取用戶輸入和代碼來顯示數組,但不是按順序。進出口,當涉及到陣列中的比較要素完全喪失:如何比較數組內的值

int getPancakes(); 
void displayArray(int theArray[],int sizeOfArray); 
void compareArray(int sizeOfArray); 
int pancakes[10]; 
int z = 0; 

int main() 
{ 
} 

int getPancakes(){ 
    int y; 
    int x = 0; 

    for(int y = 0; y < 10; y++){ 
     ++x; 
     cout << "How many pancakes did person " << x << " eat?" << endl; 
     cin >> pancakes[y]; 
    } 
} 

void displayArray(int theArray[],int sizeOfArray){ 
    for(int x = 0 ;x < sizeOfArray ; x++){ 
     ++z; 
     cout << "Person " << z << " ate " << pancakes[x] << " pancakes" << endl; 
    } 
} 

所以,我怎麼能指導我的程序到陣列中的元素比較?另外,如何指導我的程序打印每個人吃的煎餅數量列表?

+1

這功課嗎? – jterrace 2014-09-10 15:31:16

+2

另外,如果您早餐吃了10個煎餅,您可能會遇到問題。 – jterrace 2014-09-10 15:31:40

+0

我不明白。你使用'pancakes [x]'來訪問數組中的元素,但是你說你不知道如何比較數組中的元素的值?我錯過了什麼嗎? – 2014-09-10 15:41:33

回答

0

如果所有編號是唯一

int max = 0; 
for(int x = 0 ;x < 10 ; x++) 
{ 
    if(pancakes[x] > max) 
     max = pancakes[x]; 
} 
for(int x = 0 ;x < 10 ; x++) 
{ 
    if(pancakes[x] == max) 
     cout << "Person " << x << " ate " << pancakes[x] << " pancakes - biggest number" << endl; 
} 
0

爲了鈍,有兩種方法用於陣列的元素進行比較,以另一個值,直接和通過一個副本。

// Make a copy: 
    int count = pancakes[x]; 
    if (count == limit) 
    { 
    //... 
    } 

// Direct access 
    if (pancakes[x] == limit) 
    { 
    //... 
    } 
1

爲了找到誰吃了最多的煎餅,你基本上需要找到數組中最大值的位置。

int findMaxPosition(int array[], int arraySize){ 
    int maxPosition = 0;  //assume the first element is maximum 
    for(int i = 1; i < arraySize; i++) 
     if(array[i] > array[maxPosition]) //compare the current element with the known max 
      maxPosition = i; //update maxPosition 
    return maxPosition; 
} 

請注意,這會首次出現最大值。如果這些元素是獨一無二的,那就是充滿了。否則,您應該找到最大值array [maxPosition],並遍歷數組並顯示它出現的每個位置。

排序有點複雜。排序算法並不那麼簡單,我擔心如果我給你寫一個實現,我不會幫你。

最簡單的排序算法之一是冒泡排序。維基百科(http://en.wikipedia.org/wiki/Bubble_sort)有一個關於它的詳細頁面,你應該能夠使用給定的僞代碼來實現它。

0

有沒有必要穿過陣列尋找最大然後排序提供輸出。相反,你可以跟蹤您在輸入階段發現的最大價值:

int getPancakes(){ 
    int max = 0; 
    for(int y = 0; y < 10; y++){ 
     cout << "How many pancakes did person " << y << " eat?" << endl; 
     cin >> pancakes[y]; 
     if (pancakes[y]>pancakes[max]){ 
      max = y; 
     } 
    } 
    return max; 
} 

注意,我刪除的y冗餘聲明(您聲明它在for環)和x(總是將等於y)。
我還添加了函數返回值(吃掉最多的人的索引),因爲您沒有返回值。 (返回一些東西或使函數返回void(不返回))。
如果你只關心吃的最大數量,那麼你甚至不需要跟蹤最大值。相反,只需在排序步驟後從數組中讀取最大值即可。

現在,所有你需要做的是落實void sortArray()和調用顯示函數之前調用它:

int main() 
{ 
    int max = getPancakes(); 
    sortArray();    //left to you to implement 
    displayArray(pancakes,10); 
} 

你可能要考慮做煎餅本地main並將它傳遞到你的功能,在同樣的方式,你正在做displayArray