简体   繁体   English

如何在c中转换if切换案例

[英]How to convert if to switch-case in c

if(a > b)
{printf("%d is greater than %d", a, b);}
else if( a < b )
{printf("%d is greater than %d", b, a);}
else
{printf("%d is equal to %d", a, b);}

How do I convert an if statement to a switch-case in C? 如何将if语句转换为C中的switch-case? I'm trying, but i don't know the answer to this problem 我正在尝试,但我不知道这个问题的答案

switch statements are used to test an input expression against a finite set of possible values. switch语句用于根据一组有限的可能值测试输入表达式。

You're trying to compare two variables. 你试图比较两个变量。 This is not a use case for switch . 这不是switch的用例。

Your if / else if chain is fine. 你的if / else if链好了。

switch ((a < b) - (a > b)) {
case -1:
    printf("%d is greater than %d", a, b);
    break;
case 1:
    printf("%d is greater than %d", b, a);
    break;
default:
    printf("%d is equal to %d", a, b);
}

joke : 笑话

switch ((a > b) ? 1 : ((a == b) ? 0 : -1)) {
case 1:
  printf("%d is greater than %d", a, b);
  break;
case 0:
  printf("%d is equal to %d", a, b);
  break;
default:
  printf("%d is greater than %d", b, a);
}

You're stumbling on a three way comparison here. 你在这里进行三方比较是磕磕绊绊的。

You could write switch ((a < b) - (a > b)) { with -1, 0 and +1 as the case labels for a < b , a == b , and a > b respectively. 您可以将switch ((a < b) - (a > b)) {为-1,0和+1作为a < ba == ba > b的大小写标签。 Note that you need the parentheses since binary - has a higher precedence than < or > . 请注意,您需要括号,因为二进制-具有比<>更高的优先级。

In C++ that expression has been encapsulated in the three way comparison operator <=> and you could write, simply 在C ++中,表达式已经封装在三向比较运算符 <=> ,您可以简单地编写

switch (a <=> b){

with the case labels as before. 与之前的案例标签一样。 As far as I know there is no proposal to include that operator in C. 据我所知,没有建议将该运营商纳入C.

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

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