1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
using std::cout;
using std::endl;
using std::string;
using std::cin;
using std::getline;
using std::stod;
using std::invalid_argument;
using std::stringstream;
double subtract(double num_1, double num_2);
double add(double num_1, double num_2);
double multiply(double num_1, double num_2);
double divide(double num_1, double num_2);
double getUserDoubleInput();
const char * getUserOperation();
double calculate(double num_1, double num_2, const char * operation);
int main() {
double num_1;
double num_2;
const char * operation;
num_1 = getUserDoubleInput();
num_2 = getUserDoubleInput();
operation = getUserOperation();
printf("%.2f\n", calculate(num_1, num_2, operation));
return 0;
}
double subtract(double num_1, double num_2){return num_1 - num_2;}
double add(double num_1, double num_2){return num_1 + num_2;}
double multiply(double num_1, double num_2){return num_1 * num_2;}
double divide(double num_1, double num_2){return num_1 / num_2;}
double getUserDoubleInput(){
string input;
double num;
while(true) {
try {
printf("%s",
"Please Enter A Number: ");
cin.clear();
getline(cin, input);
num = stod(input);
break;
} catch (invalid_argument const &e) {
printf("%s",
"Invalid Entry\n");
}
}
return num;
}
const char * getUserOperation(){
string input;
const char * operation;
while(true) {
try {
printf("%s",
"What Operation Would You Like To Do? multiplication(*), addition(+), subtraction(-), division(/): ");
cin.clear();
getline(cin, input);
operation = input.c_str();
break;
} catch (invalid_argument const &e) {
printf("%s",
"Invalid Entry\n");
}
}
return operation;
}
double calculate(double num_1, double num_2, const char * operation){
double result = 0.0;
if(operation[0] == '-'){
result = subtract(num_1, num_2);
}else if(operation[0] == '+'){
result = add(num_1, num_2);
}else if(operation[0] == '*'){
result = multiply(num_1, num_2);
}else if(operation[0] == '/'){
result = divide(num_1, num_2);
}
return result;
}
| |