if在平时写代码的过程中是肯定会用到的,用于对条件进行判断。switch相对来说用的少一点,下面来看代码。
c/c++的写法
#include <stdio.h>
int main() {
int a = 0;
if (a > 0) { //if语句及其分支
printf("a is positive");
} else if (a == 0) {
printf("a equals 0\n");
} else {
printf("a is negative");
}
switch (a) {
case -1:
printf("a is -1");
break; // 一定要有break,否则会继续执行下面的case
case 0:
printf("a is 0");
break;
case 1:
printf("a is 1");
break;
default:
printf("input error");
}
}
java的写法
public class IfSwitch {
public static void main(String[] args) {
int a = 0;
if (a < 0) {
System.out.println("a is negative");
} else if (a == 0) {
System.out.println("a equals 0");
} else {
System.out.println("a is positive");
}
switch (a) {
case -1:
System.out.println("a is -1");
break;
case 0:
System.out.println("a is 0");
break;
case 1:
System.out.println("a is 1");
break;
default:
System.out.println("input is error");
}
}
}
go的写法
func main() {
a := 0
if a < 0 {
fmt.Println("a is negative")
} else if a ==0 {
fmt.Println("a equals 0")
} else {
fmt.Println("a is positive")
}
switch a {
case -1:
fmt.Println("a is -1")
case 0:
fmt.Println("a is 0")
case 1:
fmt.Println("a is 1")
default:
fmt.Println("input is error")
}
}
Python的写法
a = 0
if a < 0:
print("a is negative")
elif a == 0:
print("a equals 0")
else:
print("a is positive")
对比总结:
- if和switch的写法大同小异,需要注意的是,c、c++、java的switch分支需要用break,而go的不用break;
- python中大概是为了语言简洁,没有switch,使用if也能达到同样的功能。
- 使用场景:if一般使用在要判断的值有一定范围,而switch适用于要判断的值具有有限个固定值的情况。