【发布时间】:2021-07-16 07:52:34
【问题描述】:
我是 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;
}
【问题讨论】:
标签: c++ calculator