0

I don't understand what's wrong with this code.

#include <iostream> using namespace std; //Simple two number calculator //5-function calculator int main() { char aj; float a, j; cin >> a; cout << a; cin >> aj; cout << aj; cin >> j; cout << j; cout << " = "; try { if(j=0) { throw 44; } } catch (int x) { cout << x << " - can't divide by 0"; } switch(aj) { case '+': cout << a+j; break; case '-': cout << a-j; break; case '*': cout << a*j; break; case '/': cout << a/j; break; default: cout << "Error - not an operator!"; break; } return 0; }

29th Aug 2018, 4:02 AM
RA Mines
RA Mines - avatar
3 Answers
+ 8
char aj; float a, j; cin >> a; cout << a; cin >> aj; cout << aj; try { cin >> j; if(j == 0 && aj == '/') throw 0; } catch(int x) { cout << x << " - cannot divide by zero\n"; } cout << j; cout << " = "; switch(aj) { case '+': cout << a+j; break; case '-': cout << a-j; break; case '*': cout << a*j; break; case '/': cout << a/j; break; default: cout << "Error - not an operator!"; } //Corrected
29th Aug 2018, 5:50 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 6
In the try statement, you're using the assignment operator (=) instead of comparison (==). It doesn't check if j is 0, but it will set j to 0. if(x=0) always evaluates to 0 (false). So you don't catch a zero division exception, but you create one yourself by setting j to 0. For the other operations, it will return a+0, a-0 and a*0.
29th Aug 2018, 5:39 AM
Anna
Anna - avatar
+ 4
Remove the try...catch block and it will work, you can validate value of 'j' in the division case as follows: if(j == 0) { cout << "Invalid division operand (zero)"; } Hth, cmiiw
29th Aug 2018, 5:33 AM
Ipang