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
|
#include <iostream>
double add(double x, double y) { return x + y; }
double subract(double x, double y) { return x - y; }
double multiply(double x, double y){ return x * y; }
double divide(double x, double y) { return x / y; } // No error checking
typedef double (*fn)( double, double );
fn operations[] = {add, subract, multiply, divide};
const char* choices[] = { "Add", "Subract", "Multiply", "Divide" };
const unsigned int amt_choices = sizeof(choices) / sizeof(const char*);
// User input methods
double getNum();
int getInt();
int getIntInRange(int low, int high);
int main(void)
{
std::cout << "Welocome to the calculator, make a choice:\n";
for (unsigned int i = 0; i < amt_choices; i++)
std::cout << i + 1 << ") " << choices[i] << '\n';
int choice = getIntInRange(1, amt_choices);
std::cout << "Enter the first number: ";
double first = getNum();
std::cout << "Enter the second number: ";
double second = getNum();
std::cout << "The result is: " << operations[choice - 1](first, second) << '\n';
return 0;
}
double getNum(void)
{
double num;
while (!(std::cin >> num))
{
std::cin.clear();
std::cin.ignore(80, '\n');
std::cout << "Numbers only please: ";
}
std::cin.ignore(80,'\n');
return num;
}
int getInt(void)
{
double num = getNum();
while( num != static_cast<int>(num))
{
std::cout << "Integers only please: ";
num = getNum();
}
return static_cast<int>(num);
}
int getIntInRange(int low, int high)
{
int num = getInt();
while (num < low || num > high)
{
std::cout << "Must be within " << low << " and " << high << ". (Inlclusive): ";
num = getInt();
}
return num;
}
|