+ 2
Switch statement - I've not understood something
What if I want to let the user to introduce a value? Can I write greater/smaller? Or I need to use the if statement?
9 Respostas
+ 12
If your value is certain, and the range is small, you can do switch. E.g.
switch (input)
{
case 1:
case 2: // do something if input is 1 or 2
break;
case 3:
case 4:
case 5: // do something else if input is 3, 4 or 5
default: // do something if no case is satisfied
}
but if the input value is float, or has a huge range, then if statements are better:
if (input > 5 && input < 200)
+ 8
Yep, you have to use if statements to effectively evaluate large ranges. Switch statements are commonly used to evaluate variables for specific cases only.
+ 2
Yeah, ">" and "<", Matteo.
+ 2
So, if I'm using a switch statement I can't let the user choose a value of a variable (cin), isn't it?
+ 1
what value? greater/smaller? do you mean > and <?
you can use switch when you want to do different things based on the value of a variable
0
in the Hatsy's example the variable input, next to the switch, could be chosen by the user thanks to a cin >>
0
try to take a look at this code
https://code.sololearn.com/c7J0lbqhw04W/?ref=app
0
if you want to have an input from user in order to you switch statement you may try first to use ranges and if statements.
in any case I do not find it useful.
0
the if statement is ideal for that considering you have a range of values you want to work with