在开关结构中使用一系列数字 [英] Using a range of numbers in switch structure

查看:61
本文介绍了在开关结构中使用一系列数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄明白我必须有三个范围1-999 1000-1999大于2000这个程序我正在尝试写

解决方案

< blockquote>

 switchValue =  value  /  1000 ; 
switch (switchValue)
{
case 0 // 1 - 999
< span class =code-keyword> break ;
case 1 // 1000 - 1999
break ;
默认 // > 1999
break ;
}



您可能还需要在开头添加一些值为零或更少的逻辑。


如果你有连续的范围,最强有力的方法是走下楼梯而不是给出可能最终出现微妙错误的范围。例如。假设您有范围... 0,1 ... 999,1000 ... 1999,2000 ......,可能的解决方案可能来自自上而下:

  if (n> =  2000 ){
// 2000 ...
} else if (n> = 1000 ){
// 1000 ... 1999
} else if (n> = 1 ){
// 1 ... 999
} 其他 {
// ... 0
}



现在你提到你的导师了想要切换(例如出于教学原因),你可能会lculate范围指示器并在开关中使用它。例如,

 int lower_bound = n> = 2000? 2000 
:n> = 1000? 1000
:n> = 1? 1
:0
;
switch(lower_bound)
{
case 2000:
// 2000 ...
break;
case 1000:
// 1000 ... 1999
break;
案例1:
// 1 ... 999
休息;
默认值:
断言(!超出范围);
休息;
}



[/编辑]



问候

Andi


如果您的教练真的想要一个开关,那么创建类似的东西:



 < span class =code-keyword> int  switchVal; 
if (n< 1)
switchVal = 1 ;
if (n> 1&& n< 100)
switchVal = 2 ;
...
等。



现在你可以使用



  switch (switchVal){
case 1 :无论如何;
break ;
(更多等)
}





并让他/她开心。


I'm trying to figure this out I have to have three range 1-999 1000-1999 greater then 2000 for this program I'm trying to write

解决方案

switchValue = value / 1000;
switch (switchValue)
{
case 0: // 1 - 999
    break;
case 1: // 1000 - 1999
    break;
default: // > 1999
    break;
}


You may also need to add some logic for value being zero or less at the beginning.


If you have consecutive ranges, the most robust approach is to "step down the stairs" instead of giving ranges which might end up in subtle mistakes. E.g. assuming you have the ranges ...0, 1...999, 1000...1999, 2000..., a possible solution might be from top-down:

if (n >= 2000) {
  // 2000...
} else if (n >= 1000) {
  // 1000...1999
} else if (n >= 1) {
  // 1...999
} else {
  // ...0
}

[EDIT]
Now that you mention your instructor wants switch (e.g. for didactic reason), you might calculate a range indicator and use that in the switch. E.g.

int lower_bound = n >= 2000 ? 2000
                : n >= 1000 ? 1000
                : n >=    1 ?    1
                : 0
                ;
switch(lower_bound)
{
case 2000:
  // 2000...
  break;
case 1000:
  // 1000...1999
  break;
case 1:
  // 1...999
  break;
default:
  assert(!"out-of-range");
  break;
}


[/EDIT]

Regards
Andi


If your instructor really really wants a switch, then create something like:

int switchVal;
if(n<1)
  switchVal= 1;
if(n>1 && n<100)
  switchVal= 2;
... 
etc.


Now you can use

switch(switchVal) {
  case 1: whatever;
         break;
   (more etc.)     
} 



and make him/her happy.


这篇关于在开关结构中使用一系列数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆