【发布时间】:2015-02-19 21:19:45
【问题描述】:
由于我了解 Python 的基础知识 (3),所以我决定将我在 Python 中编写的程序用 C++ 键入以掌握 C++ 的窍门。
问题:当您输入“TheEnd”作为名称时,我希望程序结束,但由于某种原因,如果您输入“TheEnd”,它会询问其他字段一次,然后结尾。 有没有办法让用户在要求输入名称时输入“TheEnd”而程序刚刚结束?(我尝试将 while 循环放在不同的区域,但无济于事。)
这是我所拥有的:
#include <iostream>
#include <string>
//While loop.
using namespace std;
main()
{
string name;
string major;
float hours, qualityPoints, GPA;
while (name!="TheEnd") //Here's the while loop
{
cout<<"Please enter your name. "<<endl;
cin>>name;
cout<<"Please enter your major. "<<endl;
cin>>major;
cout<<"List the hours you've completed so far. "<<endl;
cin>>hours;
cout<<"List how many quality points you have. "<<endl;
cin>>qualityPoints;
GPA = qualityPoints / hours;
if (GPA >= 3.4 and hours >= 12)
{
cout<<name<<endl;
cout<<major<<endl;
cout<<"You made the Dean's List."<<endl;
}
else
{
cout<<"You did not make the Dean's List."<<endl;
}
}
}
【问题讨论】:
-
是的,当然有。您只需要在要求其他输入之前检查名称。
-
很好奇,你的python程序是怎么写的?无论是 python 还是 c++,您都必须检查名称。
-
阅读您的代码 - 它完全按照您的编写(当然总是如此,但这里非常清楚)
-
把
if (name == "TheEnd") break;放在cin>>name之后 -
@TonyJiang 我不确定如何向您展示我用于 Python 的代码,但它与我拥有的 C++ 代码几乎完全相同。 (我认为有一种方法可以在这个网站上发送私人消息,猜不出来。)
标签: c++ loops while-loop