我可以向用户显示程序菜单,但是我无法执行实际的数学运算。例如,当我输入2时,它仅显示0,而不是让我输入两个整数,然后将它们相乘或相加。如何获得允许用户输入1、2或3的选项,然后让其执行他们输入的操作?
#include <iostream>
using namespace std;
int main()
{
int choice;
int numberOne = 0;
int numberTwo = 0;
int sumOfTwoNumbers = 0;
int productOfTwoNumbers = 0;
do{
cout <<"Please select one of the following options: \n";
cout << "1: Enter two integer values\n"
"2: Add the two values\n"
"3: Multiply the two values\n"
"4: Exit\n";
cout << "Enter your selection (1, 2,3 or 4): ";
std::cin >> choice;
switch (choice)
{
case 1:
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
break;
case 2:
sumOfTwoNumbers = numberOne + numberTwo;
cout << sumOfTwoNumbers << endl;
break;
case 3:
productOfTwoNumbers = numberOne * numberTwo;
cout << productOfTwoNumbers << endl;
break;
case 4:
cout << "You have chosen Exit, Goodbye.";
break;
default:
cout<< "Your selection must be between 1 and 4!\n";
break;
}
}while(choice!= '4');
return 0;
}
答案 0 :(得分:1)
在情况1中,您只要求提供两个数字。在其他选项中,数字保留为默认值0
。无论选择哪个选项,都需要确保分配两个数字。另外,您的案例没有多大意义,因为所有选项都需要输入两个数字。我删除了情况1,只需移动行
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
在switch
语句上方:
cout <<"Please select one of the following options: \n";
cout <<
"1: Add the two values\n"
"2: Multiply the two values\n"
"3: Exit\n";
cout << "Enter your selection (1, 2, or 3): ";
std::cin >> choice;
cout << "Enter two integer values. " << endl;
cin >> numberOne >> numberTwo;
switch (choice)
{
case 1:
sumOfTwoNumbers = numberOne + numberTwo;
cout << sumOfTwoNumbers << endl;
break;
case 2:
//etc