为什么这只适用于休息;?

时间:2015-05-17 07:55:57

标签: loops nested-loops break

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

我的解决方案使用数组,但如果我在if语句的末尾放置一个中断,程序只会显示吃掉最多句子的人。没有休息,程序只询问每个人吃了多少然后退出。我只是想弄清楚为什么需要在那里休息,或者如果有办法在没有休息的情况下做到这一点。

这是我的代码:

//Pancakes!
#include <iostream>
#include <limits>
using namespace std;


int main()
{
    //Build array of people and set a value for most eaten
    int people[9] = {};
    int most = -1;


    for (int n=1; n<=10; n++)
    {
        //Sets the number of pancakes eaten to a person value in the array
        cout << "How many pancakes did person " << n << " eat? ";
        cin >> people[n-1];

        //Checks if the value entered above is the highest value
        if(people[n-1] > most)
        {
            most = people[n-1];
        }
    }

    //Line entered for formatting
    cout << endl;

    //Lists the person and how many pancakes they ate
    for (int x=0; x<10; x++)
    {
        if(people[x] == most)
        {
            cout << "Person " << (x+1) << " ate " << most << " pancake(s), the most!" << endl;
            break;
        }
    }




    //Pause after program
    cout << endl;
    std::cout << "Press ENTER to continue...";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

    return 0;
}

还可以随意查看我的代码,并给我提示使其更简洁,因为我仍然是新手=]谢谢。

1 个答案:

答案 0 :(得分:0)

对于上述问题,我会以这种方式解决它来预览吃最多煎饼的人:

代码:

     // assuming the first one is the highest one
    most = 0;
     //now checking for the higest one

    for (int x = 0; x < 10; x++) {
      if (people[x] > =people[most]) {
        most = x;
      }
    }

    cout << people[most]; //this shows the highest pancakes.

这根本不使用break并提供所需的输出。