That's what I had done originally however the code gets extremely long if I have an IF function for each possible number. For example
1 2 3 4 5 6 7 8 9 10
IF (operatorselector == 1){
cout << firstnum + secondnum;
input answer
IF (answer = firstnum + secondnum;
output congratulations you got it correct!
}
along with a bunch of other stuff in each IF statement. This would result in 4 of these large IF statements for each operator, which is not what I was looking for
#include <iostream>
#include <cstdlib>
usingnamespace std;
int result(int num1, int num2, int result, int sign);
int main(){
// generate random number between 1 and 4
int sign = rand() % 4 + 1;
cout << " Sign generated is: " << sign << endl;
// ask user for info
int num1=0;
int num2=0;
int answer=0;
cout << " Enter 2 numbers (with a space between them): ";
cin >> num1 >> num2;
answer = result(num1, num2, answer, sign);
cout << endl << " Answer is: " << answer << endl;
return 0;
}
// function to do the math
int result(int num1, int num2, int answer, int sign)
{
if (sign == 1)
answer= num1 + num2;
elseif (sign ==2)
answer= num1 - num2;
elseif (sign == 3)
answer= num1*num2;
elseif (sign ==4)
answer = num1/num2;
return answer;
}
#include <iostream>
typedefdouble (*FunctionPointer)(double, double);
double plus(double a, double b) {
return (a + b);
}
double minus(double a, double b) {
return (a - b);
}
double multiply(double a, double b) {
return (a * b);
}
double divide(double a, double b) {
return (a / b);
}
int main() {
enum Operator{ Plus = 0, Minus, Multiply, Divide };
constint num_operators = 4;
FunctionPointer operators[num_operators] = { plus, minus, multiply, divide };
Operator index = Plus;
/*
int min = Operator::plus;
int max = Operator::divide;
index = random(min, max);
*/
double a = 10.0;
double b = 5.0;
double value = operators[index](a, b);
std::cout << value << std::endl;
return 0;
}
EDIT - even better, put the functions in their own unique namespace. <functional> provides binary function object classes with similar names in the standard namespace (which are also cool and worth looking into) - you wouldn't want to invoke any name clashing.
Perhaps a good old switch... I call this the Obama switch...
duh = rand*4
switch (duh){
case 1: I add pain everywhere I go...
break;
case 2: I divide people by race and religion
break;
case 3: I multiply hated towards republicans and white people
break;
case 4: I subtract freedoms from Americans every chance I get.
break;
default : Somethings wrong... Of yeah, Liberials are running wild.
}