Calculator
Feb 25, 2012 at 4:37am UTC
I've looked through the history and haven't seen this particular problem. here is the code
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
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double num1;
double num2;
char op;
cout << fixed << showpoint;
cout << setprecision (2);
cout << "Enter first number: " ;
cin >> num1;
cout << endl;
cout << "Enter operator: " ;
cin >> op;
cout << endl;
cout << "Enter second number: " ;
cin >> num2;
cout << endl;
cout << num1 << op << num2;
switch (op)
{
case '+' :
cout << "=" << num1 + num2 << endl;
break ;
case '-' :
cout << "=" << num1 - num2 << endl;
break ;
case '*' :
cout << "=" << num1 * num2 << endl;
break ;
case '/' :
cout << "=" << num1 / num2 << endl;
if (num2 == 0)
cout << "ERROR" << endl;
cout << "Cannot divide by 0" << endl;
}
system ("Pause" );
return 0;
}
My problem being whenever I use the calculator to divide by 0 instead of it 'num1 / num2 = ERROR' and then next line "Cannot divide by 0" I get
'num1 / num2 =1.#J'
Any help or push in the right direction would be greatly appreciated, Thanks!
Feb 25, 2012 at 4:47am UTC
You have it divide by zero first, and THEN it checks to see if number 2 is zero. try this instead:
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
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double num1;
double num2;
char op;
cout << fixed << showpoint;
cout << setprecision (2);
cout << "Enter first number: " ;
cin >> num1;
cout << endl;
cout << "Enter operator: " ;
cin >> op;
cout << endl;
cout << "Enter second number: " ;
cin >> num2;
cout << endl;
cout << num1 << op << num2;
switch (op)
{
case '+' :
cout << "=" << num1 + num2 << endl;
break ;
case '-' :
cout << "=" << num1 - num2 << endl;
break ;
case '*' :
cout << "=" << num1 * num2 << endl;
break ;
case '/' :
if (num2 == 0)
{
cout << "=ERROR" << endl;
cout << "Cannot divide by 0" << endl;
}
else
cout << "=" << num1 / num2 << endl;
break ;
}
system ("Pause" );
return 0;
}
Last edited on Feb 25, 2012 at 4:50am UTC
Feb 25, 2012 at 4:54am UTC
Ah that makes much more sense! Thanks a lot for your help! =)
Topic archived. No new replies allowed.