how to use switch case instead of if statement ?

hi, i have this program below using switch case and i want to replace if statement that appears with switch case .. can i ?

thanks for help :)


#include <iostream>
#include <cmath>


using namespace std;


float main()
{


float left, right, result;
char op;


cout<< " Please enter two numbers and the operation as follows :\n Number ( operation ) Number" << endl;

cin>>left>>op>>right;


switch (op)

{
case 'a' : case '+':


result=left+right;
break;

case 's' : case '-' :
result=left-right;
break;

case'm' : case '*' :
result=left*right;
break;



case ('d' ) : case '/' :

if ( right==0){
cout<< " you can't divide by zero!!! \n\n";
return 0;
}

else
result=left/right;

break;


case ('%') :
result=fmod(left, right );

break;

}

cout<< " The Result is : " << result<< endl;

return 0;




}
Last edited on
1
2
3
4
5
6
7
if ( right==0){
cout<< " you can't divide by zero!!! \n\n";
return 0;
}

else
result=left/right;


becomes

1
2
3
4
5
6
7
8
9
switch(right)
{
 case 0: cout<< " you can't divide by zero!!! \n\n";
     return 0;
     break;
default:
    result=left/right;
    break;
 }



i tried this way but it showed me this error :
" error C2450: switch expression of type 'float' is illegal " ?

is there any way to solve it without changing " float " ?
Oop. Didn't notice it was a float.

Comparing a float to zero doesn't always work out.
http://floating-point-gui.de/
and in particular
http://floating-point-gui.de/errors/comparison/

1
2
3
4
5
6
7
8
9
switch(right == 0) // this will need to be more clever that this for some circumstances
{
 case 1: cout<< " you can't divide by zero!!! \n\n";
     return 0;
     break;
default:
    result=left/right;
    break;
 }


float main()

main should return an int, not a float.
moschops :

it's nicely done!
thanks alot .. :)
Last edited on
Topic archived. No new replies allowed.