C++ 程序菜单使用做同时和切换

C++ Program menu using do while and switch

本文关键字:程序 菜单 C++      更新时间:2023-10-16

我能够向用户显示程序菜单,但我无法执行实际的数学运算。例如,当我输入 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 valuesn"
"2: Add the two valuesn"
"3: Multiply the two valuesn"
"4: Exitn";
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;
}

在情况 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 valuesn"
"2: Multiply the two valuesn"
"3: Exitn";
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