从learncpp.com做基本练习,输出"最少数量"在Pancake Glutton是不对的

时间:2017-09-25 16:15:41

标签: c++

我目前正在学习C ++,并希望进行以下练习: 需要:

变量,数据类型和数字运算符 基本输入/输出 逻辑(if语句,switch语句) 循环(for,while,do-while) 阵列

写一个程序,要求用户输入由10个不同的人(第1人,第2人,......,第10人)吃早餐的煎饼数量 一旦输入数据,程序必须分析数据并输出哪个人吃早餐最煎饼。

★修改程序,以便输出哪个人吃早餐的煎饼数量最少。

★★★★修改程序,使其按照所有10个人吃的煎饼数量顺序输出一个列表。 即 人4:吃了10个煎饼 人3:吃了7个煎饼 人8:吃了4个煎饼 ... 人5:吃了0个煎饼

Sofar我已经得到了#34;吃得最多"并且"第二多",但我遇到了问题"最少"部分...

这是我的代码:

#include <iostream>
using namespace std;
int arrayPersonsPancakes[]={};
int arrayPersonsNr;

int createArrayforPersons();
void pancakesPerPerson(int);
void whoAteTheMost();


int main(){
int arrayPersonsNr = createArrayforPersons();
pancakesPerPerson(arrayPersonsNr);
whoAteTheMost();

/*for(int i=0; i < arrayPersonsNr; i++){
   cout << arrayPersonsPancakes[i] << endl;
}*/

}

int createArrayforPersons(){
cout << "Please enter the Nr. Of Persons who ate breakfast: " << endl;
int nrOfPersons;
cin >> nrOfPersons;
arrayPersonsPancakes[nrOfPersons];
return nrOfPersons;
}

void pancakesPerPerson(int nrOfPersons){
for (int i=0; i < nrOfPersons; i++){
    cout << "Please enter how many pancakes person Nr." << i+1 << " ate: " << endl;
    cin >> arrayPersonsPancakes[i];
    }

}
void whoAteTheMost(){
    int theMost= arrayPersonsPancakes[0];
    int theSecondMost;
    int theLeast;
for(int i = 0; i < arrayPersonsNr; i++){
    if (arrayPersonsPancakes[i] > theMost){
        theSecondMost = theMost;
        theMost = arrayPersonsPancakes[i];
                }
    }

theLeast = theMost;

 cout << theLeast << endl; //Here I get the normal output

for(int y = 0; y < arrayPersonsNr; y++){
    if (theLeast >  arrayPersonsPancakes[y]) {
        theLeast = arrayPersonsPancakes[y];
    }
}

cout << "after for " << theLeast << endl;  //I always get a zero here after the loop and have no idea why.
}

for(int j = 0; j < arrayPersonsNr; j++){
    if (arrayPersonsPancakes[j] == theMost){
        cout << "Person Nr." << j+1 << " ate the most Pancakes: " << theMost << endl;}
    else if (arrayPersonsPancakes[j] == theSecondMost){
        cout << "Person Nr." << j+1 << " ate the second most Pancakes: " << theSecondMost << endl;}
   else if (arrayPersonsPancakes[j] == theLeast){
        cout << "Person Nr." << j+1 << " ate the least Pancakes: " << theLeast << endl;}

    }
}

Loop for&#34; theleast&#34;无论我做什么,我总是得到零。 我对如何编写代码以及如何改进代码表示感谢(无论当前是否缺少评论,对此感到抱歉)

谢谢!

1 个答案:

答案 0 :(得分:0)

您正在主要功能

中创建局部变量arrayPersonsNr
int main(){    
        int arrayPersonsNr = createArrayforPersons(); // This is local variable
        pancakesPerPerson(arrayPersonsNr);
        whoAteTheMost();
    }

将代码修改为

int main(){
    arrayPersonsNr = createArrayforPersons(); // This is global variable
    pancakesPerPerson(arrayPersonsNr);
    whoAteTheMost();
}