how to use switch case instead of if statement ?

Oct 21, 2012 at 11:13am
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 Oct 21, 2012 at 11:33am
Oct 21, 2012 at 11:49am
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;
 }



Oct 21, 2012 at 12:11pm
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 " ?
Oct 21, 2012 at 12:51pm
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;
 }
Oct 21, 2012 at 1:06pm


float main()

main should return an int, not a float.
Oct 21, 2012 at 8:23pm
moschops :

it's nicely done!
thanks alot .. :)
Last edited on Oct 21, 2012 at 8:24pm
Topic archived. No new replies allowed.