2014-09-10 105 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