zoukankan      html  css  js  c++  java
  • 使用if语句时应注意的问题(初学者)

    (1)在三种形式的if语句中,在if关键字之后均为表达式。该表达式通常是逻辑表达式或关系表达式,但也可以是其他表达式,如赋值表达式等,甚至也可以是一个变量。

    例:if(a=5)语句;

           if(b)语句;

    只要表达式的值为非零,即为“真”。

    比较:

    #include<stdio.h>
    
    void main()
    {
        int a,b;
        scanf("%d%d",&a,&b);
        if (a=b)
        {
            printf("%d
    ",a);
        }
    }
    #include<stdio.h>
    
    void main()
    {
        int a,b;
        scanf("%d%d",&a,&b);
        if (a==b)
        {
            printf("%d
    ",a);
        }
    }

     注;若if后的a==5输入成a=5,则输出结果永远为真。

    如何避免:将a==5改为5==a(习惯上的改变,这只是一个例子)

    (2)在if语句中,条件判断表达式必须用括号括起来,在语句之后必须加分号。

    (3)在if语句的三种形式中,所有的语句应为单个语句,如果想要在满足条件时执行一组(多个语句),则必须把这一组语句用{}括起来组成一个复合语句。但要注意的是在}后不能再加;号。(建议单个语句也用{}括起来,方便以后插入新语句)

    例:

    #include<stdio.h>
    
    void main()
    {
        int a,b;
        scanf("%d%d",&a,&b);
        if (a>b)
        {
            a++;
            b++;
        }
        else
        {
            a=0;
            b=10;
        }
        printf("%d,%d",a,b);
    }

    补例1:写一个程序完成下列功能:

    1、输入一个分数score;

    2、score<60      输出E

    3、60<=score<70             输出D

    4、70<=score<80     输出C

    5、80<=score<90             输出B

    6、90<=score      输出A

    #include<stdio.h>
    
    void main()
    {
        int score;
        printf("input a score
    ");
        scanf("%d",&score);
        if(score<60)
        {
            printf("The score is E");
        }
        else if((score>60 || score==60)&&score<70)
        {
            printf("The score is D ");
        }
        else if((score>70 || score==70)&&score<80)
        {
            printf("The score is C");
        }
        else if((score>80 || score==80)&&score<90)
        { 
            printf("The score is B");
        }
        else if(score>90||score==90)
        {
            printf("The score is A");
        }
    }

    补例2:输入3个数a,b,c,要求按由小到大的顺序输出。

    提示:if  a>b  将a和b互换;

         if  a>c  将a和c互换;

         if  b>c  将b和c互换;

    #include<stdio.h>
    
    void main()
    {
        int a,b,c,temp;
        printf("input three numbers
    ");
        scanf("%d%d%d",&a,&b,&c);
        if(a>b)
        {
            temp=a;
            a=b;
            b=temp;
        }
        if(a>c)
        {
            temp=a;
            a=c;
            c=temp;
        }
        if(b>c)
        {
            temp=b;
            b=c;
            c=temp;
        }
        printf("%d %d %d 
    ",a,b,c);
    }
  • 相关阅读:
    Windows 显示隐藏文件
    Python 程序一行代码解决乘法口诀表
    【转发】基于Bert-NER构建特定领域的中文信息抽取框架(上)
    【转发】GET和POST两种基本请求方法的区别
    【转发】实现yolo3模型训练自己的数据集总结
    第十章集合总结
    2016-2017 201671010134 异常处理
    JAVA基础编程
    2016-2017 201671010134 第六章总结
    java总结
  • 原文地址:https://www.cnblogs.com/lvfengkun/p/10217437.html
Copyright © 2011-2022 走看看