您的位置 首页 golang

golang2021流程控制(10if-elseif与switch比较

其实通过上面的案例,我们发现switch能够实现的,我们用if-else if也可以实现,那么反过来呢,if-else if能实现的,我们使用switch能否实现呢?接下来将我们前面用if-else if实现的“考试成绩评定”这道题用switch来实现。

总结:

相同点:都可以实现多分支结构

不同点(根据个人习惯进行选择):

if-else if:可以处理范围

switch:一般用于等值比较

 

下面我们通过一个练习题,将if-else和switch结构进行综合应用

(5.3)练习:请用户输年份,再输入月份,输出该月的天数.(结合之前如何判断闰年来做)

funcmain(){

    //请用户输年份,再输入月份,输出该月的天数.

    varyearint//表示年份

    varmonthint//表示月份

    vardayint

    fmt.Println(“请输入年份”)

    fmt.Scanf(“%d\n”,&year)

    fmt.Println(“请输入月份”)

    fmt.Scanf(“%d”,&month)

    //判断月份的取值范围

    ifmonth>=1&&month<=12{

        switchmonth{

        case1:

            fallthrough

        case3:

            fallthrough

        case5:

            fallthrough

        case7:

            fallthrough

        case8:

            fallthrough

        case10:

            fallthrough

        case12:

            day=31

        case2://需要判断是否为闰年

            if(year%400==0)||(year%4==0&&year%100!=0){

                day=29

            }else{

                day=28

            }

        default:

            day=30

        }

        fmt.Printf(“%d年%d月共%d天”,year,month,day)

    }else{

        fmt.Println(“月份输入错误!!”)

}

通过上面的案例,我们发现switch结构和if-else结构是可以结合来使用的,可以根据具体的问题具体分析,灵活来应用。

文章来源:智云一二三科技

文章标题:golang2021流程控制(10if-elseif与switch比较

文章地址:https://www.zhihuclub.com/98390.shtml

关于作者: 智云科技

热门文章

网站地图