0

我想在 switch 语句中使用逻辑运算符。
例如:
“x 大于 3 且小于 7”
在 If 语句中使用它。

if(x > 3 && x < 7)
  {
    //something
  }else if(x 11 3 && x < 15){
         // anything
  }

如何在 switch 语句中使用它。
以及如何使用算术运算符。
更新
现在我们如何在 switch 中使用它。有没有办法在switch中使用它。

4

1 回答 1

2

You mean, something like this?

switch (some_var)
{ case 4 : // fall through
  case 5 : // fall through
  case 6 : do_something();
          break;
  default : do_something_else();
           break;
}

It's ugly, and gets worse the larger a range you want to cover, but since switch cases must be constants, that's one way to do it.

Another way would be:

switch ((some_var > 3) && (some_var < 7))
{ case 0: do_something_else(); break;
  default: do_something(); break;
}

But that'll only work if you have exactly one range you want to test. There are other ways if you have a set of equally-sized intervals that are spaced equally far apart, using some basic arithmetic, but we'd have to know a bit more about the specific problem(s) you're trying to solve...

Frankly, though, I think the if construct is the better solution...

于 2013-11-12T18:24:53.813 回答