#include <iostream>
using namespace std;
int main()
{
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
switch(operation)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
if(response=='Y')
{
here
}
else if(response=='N')
{
cout << "The program will now close" << endl;
system("sleep 500");
return -1;
}
return 0;
}
如果写“here”这个词,我想插入一个代码,让你接受代码的开始。
答案 0 :(得分:2)
您可以使用循环do... while(condition)
喜欢:
do{
cin >> a >> operation >> b;
switch(operation)
{
...
}
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
}while(response=='Y');
如果响应不是'Y',则循环结束,如果循环再次开始
答案 1 :(得分:2)
尽管goto
在C ++中非常不受欢迎,但确实存在。
就像装配一样,你在你的代码中加上一个标签,然后告诉它跳过&#39;使用goto
。但是,跳转在程序集中的工作方式相同,这可能会使您从所有循环中突破到跳转到的位置。
#include <iostream>
using namespace std;
int main()
{
label:
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
//condensed for neatness
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
if(response=='Y')
{
goto label;
}
else if(response=='N')
{
cout << "The program will no`enter code here`w close" << endl;
system("sleep 500");
return -1;
}
return 0;
}
大多数人会做的是使用do{}while(condition==true)
循环或仅使用无限循环while(true)
。
对于这个&#39; neater&#39;代码,你要做的是
#include <iostream>
using namespace std;
int main()
{
do{
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
//condensed for neatness
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
}while(cin.get() == 'Y');
cout << "The program will no`enter code here`w close" << endl;
system("sleep 500");
return -1;
return 0;
}
如果从另一个位置调用它,我强烈建议使用do而不是goto,因为它可能会导致问题。
goto唯一真正的问题是它不优雅并且使代码难以阅读。您应该尽可能使用循环并返回,如果您没有其他方法可以使此工作达到最佳效果,则只能使用goto。