我是c++的初学者,我的任务是创建一个计算器并要求用户输入数字以进行计算。另外,我还需要创建一个代码来处理用户输入错误的情况,即程序将要求用户输入正确的数字。如何写一个处理用户输入错误的代码,使整个代码重复执行。
#include <iostream>
using namespace std;
int UI() {
int choice;
cout << "Enter the correspendonce number for the following options you want "
": \n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n\n "
"Option: ";
cin >> choice;
return choice;
}
int add(int a, int b) {
int c = a + b;
return c;
}
int subtract(int a, int b) {
int c = a - b;
return c;
}
int multiply(int a, int b) {
int c = a * b;
return c;
}
int divide(int a, int b) {
int c = a / b;
return c;
}
// main function
int main() {
int total;
int num1, num2;
int choice;
choice = UI();
if (choice == 1) {
cout << "Input two numbers you wish to calculate for :";
cin >> num1;
cin >> num2;
total = add(num1, num2);
cout << " the total is " << total << "\n";
} else if (choice == 2) {
cout << "Input two numbers you wish to calculate for :";
cin >> num1;
cin >> num2;
total = subtract(num1, num2);
cout << " the total is " << total << "\n";
} else if (choice == 3) {
cout << "Input two numbers you wish to calculate for :";
cin >> num1;
cin >> num2;
total = multiply(num1, num2);
cout << " the total is " << total << "\n";
} else if (choice == 4) {
cout << "Input two numbers you wish to calculate for :";
cin >> num1;
cin >> num2;
total = divide(num1, num2);
cout << " the total is " << total << "\n";
} else {
cout << "Entered wrong input, please select option 1 - 5";
}
return 0;
}