我正在参加cplusplus.com初学者练习,以使用我在c ++中学到的知识。我想出了Pancake Glutton练习。
Pancake Glutton
要求: 变量,数据类型和数字运算符 基本输入/输出 逻辑(if语句,switch语句) 循环(for,while,do-while) 阵列
写一个程序,要求用户输入由10个不同的人(第1人,第2人,......,第10人)吃早餐的煎饼数量 一旦输入数据,程序必须分析数据并输出哪个人吃早餐最煎饼。
★修改程序,以便输出哪个人吃早餐的煎饼数量最少。
★★★★修改程序,使其按照所有10个人吃的煎饼数量顺序输出一个列表。
我的程序解决了这个问题,但我这样做了用户插入的人数。我的问题是当程序找到吃最少量的煎饼的人时,我的程序崩溃了。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int people,i,maxi=0,cakes, mini=0;
string name,glutton,nibbler;
int main()
{
//Ask user the amount of people that have eaten pancakes
cout<<"How many people have eaten pancakes? \n";
cin>>people;
//Assign the names of each person that ate pancakes
string names[people];
for(i=0;i<people;i++){
cout<<"Name? ";
cin>>name;
names[i]=name;
}
cout<<endl;
//Ask how many pancakes each person has eaten
int nums[people];
for(i=0;i<people;i++){
cout<<"How many pancakes did "<<names[i]<<" eat?"<<endl;
cin>>cakes;
nums[i]=cakes;
}
cout<<endl;
//Compare to take the person that ate the most
for(i=0;i<people;i++){
if(nums[i]>maxi){
maxi=nums[i];
glutton=names[i];
}
}
mini=maxi;
/*I assigned the value of max to mini to make starting
*point of comparison to look for the one that ate the
*least
*/
//Compare for the person that ate the least
/**This is what makes my program explode, and I don't know why*/
for(i=0;i<people;i--){
if(nums[i]<mini){
mini=nums[i];
nibbler=names[i];
}
}
cout<<glutton<<" ate the most"<<endl;
cout<<nibbler<<" ate the least"<<endl;
return 0;
}
答案 0 :(得分:-1)
基本上我发现我可以使用数组中的位置来缩短代码,更容易理解并且显然更快。我知道这种程序记忆没什么关系,但我应该从一开始就养成习惯。
#include <iostream>
#include <string>
using namespace std;
int people,i,glutton=0,cakes,nibbler=0;
string name;
int main()
{
//Ask user the amount of people that have eaten pancakes
cout<<"How many people have eaten pancakes? \n";
cin>>people;
//Assign the names of each person that ate pancakes
string names[people];
for(i=0;i<people;i++){
cout<<"Name? ";
cin>>name;
names[i]=name;
}
cout<<endl;
//Ask how many pancakes each person has eaten
int nums[people];
for(i=0;i<people;i++){
cout<<"How many pancakes did "<<names[i]<<" eat?"<<endl;
cin>>cakes;
nums[i]=cakes;
}
cout<<endl;
//Compare to take the person that ate the most and the least
for(i=1;i<people;i++){
if(nums[i]>nums[glutton]){
glutton=i;
}
if(nums[i]<nums[nibbler]){
nibbler=i;
}
}
cout<<names[glutton]<<" ate the most"<<endl;
cout<<names[nibbler]<<" ate the least"<<endl;
return 0;
}