为什么这只适用于 break;?
Why will this only work with break;?
1) 编写一个程序,要求用户输入 10 个不同的人(第 1 人、第 2 人、...、第 10 人)早餐吃的煎饼的数量。
输入数据后,程序必须分析数据并输出哪个人早餐吃煎饼最多。
我的解决方案使用数组,但如果我在 if 语句的末尾放置一个 break,程序只会显示吃最多句子的人。没有休息,程序只询问每个人吃了多少然后退出。我只是想确切地了解为什么需要休息,或者是否有办法在没有休息的情况下做到这一点。
这是我的代码:
//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;
}
也可以随时查看我的代码,并给我提示以使其更简洁,因为我还是个新手 =] 谢谢。
上面的问题,我会这样解,先看看吃煎饼最多的人:
代码:
// 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 并提供所需的输出。
1) 编写一个程序,要求用户输入 10 个不同的人(第 1 人、第 2 人、...、第 10 人)早餐吃的煎饼的数量。 输入数据后,程序必须分析数据并输出哪个人早餐吃煎饼最多。
我的解决方案使用数组,但如果我在 if 语句的末尾放置一个 break,程序只会显示吃最多句子的人。没有休息,程序只询问每个人吃了多少然后退出。我只是想确切地了解为什么需要休息,或者是否有办法在没有休息的情况下做到这一点。
这是我的代码:
//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;
}
也可以随时查看我的代码,并给我提示以使其更简洁,因为我还是个新手 =] 谢谢。
上面的问题,我会这样解,先看看吃煎饼最多的人:
代码:
// 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 并提供所需的输出。