if 和 else

前序:

    float a = 3.14;
    float b = 42.0;
    double result = a + b ;
    printf("the result is %f \n",result);

导图如下:


if 和 else.png

深入学习:

#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...

    //定义一个卡车重量的变量
    float truckWeight = 34567.1;
    
    //根据卡车重量判断是否属于轻型货车
    if (truckWeight < 40000.0) {
        printf("It is a light truck\n");
    }else{
        printf("It is a heavy truck\n");
    }
    return 0;
}

布尔变量:

BOOL isNotLegal = ((truckWeight > 0.0) && (truckWeight < 40000.0));
    if (isNotLegal) {
        printf("truck weight is legal range.\n");
    }

三元运算符:

 int minutesPerPound;
    if (isNotLegal) {
        minutesPerPound = 10;
    }else{
        minutesPerPound = 20;
    }
    
    //可以用下面的三元运算符代替
    minutesPerPound = isNotLegal?10:20;
    
    printf("the minutesPerPound is %d.\n",minutesPerPound);

练习题:
阅读下面这段代码:

int i = 20;
    int j = 25;
    
    int k = (i > j) ? 10 : 5;
    if (5 < j - k) {
        printf("the first experssion is true.");
    }else if (j > i){
        printf("the second experssion is true.");
    }else{
        printf("Neither expression is true.");
    }

试写出控制台的输出结果。

第一个答出结果的有红包发送哦。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容