使用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\n",a);
    }
}
#include<stdio.h>

void main()
{
    int a,b;
    scanf("%d%d",&a,&b);
    if (a==b)
    {
        printf("%d\n",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\n");
    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\n");
    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 \n",a,b,c);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM