I ran your program and got a floating point exception. The floating point exception is due to
Since you don't initialize a or b to anything, this is initially 0 / 0 which is NaN (not a number). If you simply cast a or b to a floating point number in this equation:
|
int quotient = static_cast<double>(a) / b;
|
or
|
int quotient = a / static_cast<double>(b);
|
The floating point exception goes away. This is because if either a or b is a floating point, when the operation is done, it promotes the other to a floating point.
If you simply make b initialized to something other than 0, the floating point exception also goes away. If you divide a number by zero it is either NaN of +/- infinity, which is not an integer.
Keeping a and b both at zero and simply changing quotient to a double won't fix it (i.e.
double quotient = a/b;
because when a / b is initially calculated both a and b are int's so the solution is of type int and only after it is calculated is the solution (assigned to the variable quotient) converted to a floating point number. Look through type conversion in a C++ book, operations are best done with float or double because 5/2 = 2 with ints.
Also, you are correct that your if/else has problems and so does you cin and you also need to recompute sum/difference/etc. after you read a and b in. As for your if/else,
if(sum)
(and all the other else if's) convert the variable in the parentheses to a boolean (meaning it can only have the value of 0 or 1). For boolean's 0 = false, 1 = true. If another type is converted to a boolean, 0 = false and anything other than zero evaluates to true.
Keeping things as simple as possible, what you actually want to do is make a string called operation. Read in operation, and use that for your if/else:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <string>
...
double a = 0., b = 1.;
string operation = "+";
cout << "Enter a number" << endl;
cin >> a;
cout << " enter another number" << endl;
cin >> b;
cout << "enter an operation (+, -, *, /, sq)" << endl;
cin >> operation;
if(operation == "+")
cout << "The sum is " << (a+b) << endl;
else if(operation == "-")
cout << "The difference is " << (a-b) << endl;
...
else if(operation == "sq")
cout << "The square is " << (a*a) << endl;
else
cout << "Not a valid operation. Valid operations are +, -, *, /, sq" << endl;
|
By the way, system("pause") works on Windows but this doesn't work on most UNIX systems. You may not care about cross-platform compatibility right now but it's generally bad practice to do so.