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
|
#include <iostream>
// function references
template <typename T> T calculate(T num1, char sym, T num2);
template <> int calculate(int num1, char sym, int num2); // Do I need the template <> part? The stack overflow post had it.
int main() {
std::cout << "Note: Please make sure both numbers are the same data type (int, float, double).\n";
std::cout << "Please input a number, symbol, and another number (i.e. 5 * 4): ";
auto n1 = 0.0, n2 = 0.0;
char symbol = ' ';
std::cin >> n1 >> symbol >> n2;
std::cout << "Answer: " << calculate(n1, symbol, n2) << '\n';
return 0;
}
// Will solve math problem user gives program no matter which data type the
// numbers are (int, float, double).
template <typename T>
T calculate(T num1, char sym, T num2) {
if (sym == '*' || sym == 'x') {
return num1 * num2;
}
else if (sym == '/') {
return num1 / num2;
}
else if (sym == '+') {
return num1 + num2;
}
else if (sym == '-') {
return num1 - num2;
}
else {
std::cout << "Error! symbol is not *, x, /, +, or -. Are you sure you input the correct symbol? \n";
exit(1);
}
}
// Overloads above function, so it will do ^ if double or float and will do the below if int.
template <>
int calculate(int num1, char sym, int num2) {
if (sym == '*' || sym == 'x') {
return num1 * num2;
}
else if (sym == '/') {
return num1 / num2;
}
else if (sym == '+') {
return num1 + num2;
}
else if (sym == '-') {
return num1 - num2;
}
// The unique line:
// '%' only works with ints.
else if (sym == '%') {
return num1 % num2;
}
else {
std::cout << "Error! symbol is not *, x, /, +, -, or %. Are you sure you input the correct symbol? \n";
exit(1);
}
}
|