C/C++、Java、Go、Python总结对比21-if和switch

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")

对比总结:

  1. if和switch的写法大同小异,需要注意的是,c、c++、java的switch分支需要用break,而go的不用break;
  2. python中大概是为了语言简洁,没有switch,使用if也能达到同样的功能。
  3. 使用场景:if一般使用在要判断的值有一定范围,而switch适用于要判断的值具有有限个固定值的情况。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值