问题描述
在主体中 getwhattheywant 函数执行两次我想要的问题是 getwhattheywant 执行然后用户输入一个然后如果用户输入一个做求和操作但是我发生了什么它正在重新要求用户输入一个数字。
#include <iostream>
using namespace std;
double dothesum(int x,int y)
{
int sum = x + y;
return sum;
};
int getwhatheywant()
{
int choice;
cout << "1- for sum " << endl;
cout << "2- for quit ";
cin >> choice;
return choice;
}
void the_sum()
{
int x,y;
cout << " enter the first number " << endl;
cin >> x;
cout << " enter the second number " << endl;
cin >> y;
cout << " the sum of the two number is " << dothesum(x,y) << endl;
}
int main()
{
int;
while (getwhatheywant() != 2) {
if (getwhatheywant() == 1) {
the_sum();
}
}
return 0;
}
解决方法
更改您的 main():
int main()
{
int whatTheyWant;
while ( (whatTheyWant = getwhatheywant()) != 2) {
if (whatTheyWant) == 1) {
the_sum();
}
}
return 0;
}
这会存储对 getwhattheywant() 的单个调用的值,因此您可以首先查看他们是否要求退出,如果没有,您可以查看他们可能还想要什么。现在,我的写法略有不同:
bool working = true;
while(working) {
int choice = getWhatTheyWant();
switch(choice) {
case 1: the_sum(); break;
case 2: working = false; break;
}
}