【发布时间】:2018-01-08 16:45:47
【问题描述】:
我正在参加 cplusplus.com 初学者练习,以使用我在 C++ 中学习的内容。我想出了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;
}
【问题讨论】:
-
int people...string names[people];--int nums[people];-- 这不是有效的 C++。在 C++ 中,数组是使用编译时常量声明的,以表示数组中的条目数,而不是像int people这样的变量。变量数组是在 C++ 中使用std::vector完成的。 -
for(i=0;i<people;i--)这永远不会终止。 -
使用调试器单步调试代码,看看哪里出错了。另请参阅 Eric Lippert 的 How to debug small programs
-
@MikeHarris 你考虑过整数下溢吗?您的陈述将不适用于整数下溢导致最高可能值的那些(可能广泛传播的)环境。
-
@Yunnosch 你是对的,当然。当整数换行时,循环将终止。更大的问题是,在第一次迭代之后,
i的值将是 -1,这将导致nums[i]取消引用出现问题。程序可能会在整数溢出之前崩溃。
标签: c++