简体   繁体   English

将Switch语句转换为if / then和if / else语句

[英]Turn Switch statement into if/then and if/else statement

I want to make this switch statement into if/else and if/then statement. 我想将此switch语句转换为if / else和if / then语句。 My Switch statement is : 我的Switch语句是:

char option;
printf("Choose your option : ");
scanf("%c",&option);

switch(option){
    case 'a':
    case 'A': a = 20 + 10 ;
        printf("Addition process result:%d",a);
        break;
    case 'b':
    case 'B': a = 20 - 10 ;
        printf("Subtraction process result:%d",a);
        break;
    case 'c':
    case 'C': a = 20 * 10 ;
        printf("Multiplication process result:%d",a);
        break;
    case 'd':
    case 'D': a = 20 + 10 ;
        printf("Division process result:%d",a);
        break;
    default:
        printf("Invalid option");
    }

You just do: 您只需:

if(option == 'a' || option == 'A') {
    // do whatever
}
else if (option == 'b' || option == 'B') {
    // do whatever
}

... the other else if's ...其他如果

then for the "invalid option", you have just an else {}. 那么对于“无效选项”,您只有一个else {}。 If the first if or any of the subsequent else if's evaluate true, then all the others will be skipped. 如果第一个if或随后的else的任何if的评估结果为true,则将跳过所有其他if。

like this: 像这样:

#include <stdio.h>

int main() {
    char option;
    printf("Choose your option : ");
    scanf("%c",&option);

    if (option == 'a' || option == 'A') {
        int a = 20 + 10;
        printf("Addition process result:%d", a);
    } else if (option == 'b' || option == 'A') {
        int a = 20 - 10;
        printf("Subtraction process result:%d", a);
    } else if (option == 'c' || option == 'C') {
        int a = 20 * 10;
        printf("Multiplication process result:%d", a);
    } else if (option == 'd' || option == 'D') {
        int a = 20 + 10;
        printf("Division process result:%d", a);
    } else {
        printf("Invalid option");
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM