if 和 else

前序:

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

导图如下:


if 和 else_第1张图片
if 和 else.png

深入学习:

#include 

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.");
    }

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

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

你可能感兴趣的:(if 和 else)