How can I write
if(x%26gt;1 %26amp;%26amp; x%26lt;3)
{
statement;
}
with just a switch in C++ without using any of (if) structures! x is a double or a float not an integer
Thanks
How can I write this switch in C++?
is far as my expirence goes you cannot use floating point numbers in a switch statement and expect stable results.
Since there are many stages between 1 and 2 with floating point numbers you'd have to try to cover each one of these cases in a switch statement. Going with if structures will be far more reliable. I have only ever seen and used switch statements used with integers. Infact im pretty certain that you'll at the very least get a warning from the compiler if you try to use a float or double in a switch statement.
Reply:Use this:
switch( (int)(Math.abs(x-2)) )
{
case 0:
{ the true condition statements }
break;
default:
break;
}
The case 0 will be used when
abs(x-2) %26lt; 1
Use algebra to expand this
|x-2| %26lt; 1
-1 %26lt; x-2 %26lt; 1
1 %26lt; x %26lt; 3
Which is what you want.
Reply:switch(x)
{
case 2:
statements;
break;
default:
statements;
break;
}
augustifolia
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment