在Switch语句中转换IF语句

时间:2017-03-17 08:33:58

标签: c if-statement switch-statement expression control-flow

我有一系列IF语句,我想在Switch语句中进行转换,但是我无法在switch的constant1字段中插入评估。

我知道Switch的工作方式是这样的:

switch ( expression ) {   //in my case:      switch (score) {
  case constant1:
    statement
      break;
  case constant2:
    statement
  default:
    statement
      break;

现在我试图将<= 60放在constant1字段中,但当然它不起作用。

这是我要在Switch中转换的一系列IF语句。

if (score <= 60) {
    printf("F");
}
if (score <= 70 && score > 60) {
    printf("D");
}
if (score <= 80 && score > 70) {
    printf("C");
}
if (score <= 90 && score > 80) {
    printf("B");
}
if (score <= 100 && score > 90) {
    printf("A");
}

感谢所有人!

6 个答案:

答案 0 :(得分:4)

switch语句采用常量,而不是条件。例如,您不能说>= const,因此您需要更改策略。

例如,在您的情况下,您可以在从中减去1之后打开两位数分数的第一位数字:

switch ((score-1) / 10) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5: printf("F"); break;
    case 6: printf("D"); break;
    case 7: printf("C"); break;
    case 8: printf("B"); break;
    case 9: printf("A"); break;
}

案例0..4对切换语句使用C的直通机制,全部打印"D"

以上代码假设您已将分数范围检查为1..100(含)。

答案 1 :(得分:0)

正如评论中所述,你不能这样做,因为在switch语句中,你只能有1个表达。

使用if-else语句,如下所示:

if (score <= 60) {
    printf("F");
} else if (score <= 70) {
    printf("D");
} else if (score <= 80) {
    printf("C");
}
//More statements

启用了开关的GCC扩展,您可以这样使用:

switch (score) {
    case 0...60:
        break;
    case 61...70:
        break;
    //..More cases with range
}

答案 2 :(得分:0)

switch仅检查是否相等。因此,在您的情况下,if-else构造更适合。

但是,如果你想使用switch语句,你必须这样做:

switch (score) 
{
  case 0:
  case 1:
  case 2:
  ... // all cases up to 58
  case 59:
  case 60:
    printf("F");
    break;
  case 61:
  ...
}

不是很漂亮也很乏味。

答案 3 :(得分:0)

正确的语法为case *constant*,因此您无法编写case < 60

你可以做的是,将几个案例命令放在彼此之下,如下所示:

case 40:
case 41:
case 42:
case 43:
    // do stuff
break;

如果switch语句等于40,41,42或43,这将“do stuff”。但是,我可以建议,除非你有充分的理由将if语句转换为switch语句,否则你不应该'在这个特殊的场合。

答案 4 :(得分:0)

您可以使用ifswitch,或者只需:

 printf("%c", 70 - ((score - 60) > 0 ? (score - 41) / 10 : 0));

Live example on ideone.com

P.S。当然,在switch语句中可以使用类似的内容,恰好有五个case

答案 5 :(得分:0)

有点偏离。 你可以尝试跟随伪。它简短而简单。

char cGrade = 9-(score/10)+65;
if( cGrade > 68 )
{
    cGrade = 70; // for 'F'
}
else if( cGrade < 65 )
{
    cGrade = 65; // for 'A'
}