c++ if語句講解&例題


一.if語句

1.基本語法:

if(條件 布爾型){
    當條件符合執行的語句 
} 

 2.例子:

#include <iostream>
using namespace std;
int main(){
    int a;
    a = 20;
    if(a > 10){ // ">" 是大於 
        cout << "a大於10";
    }
}

輸出:

a大於10

 

3.例題:

描述:

輸入一個數a

如果a是奇數,輸出"jishu"

如果a是偶數,輸出"oushu"

代碼:

#include <iostream>
using namespace std;
int main(){
    int a;
    cin >> a;
    if(a%2 == 1){ // %號是求余 
        cout << "jishu";
    }
    if(a%2 == 0){
        cout << "oushu";
    }
}

 

二.if else語句

1.基本語法

if(條件 布爾型){
    當條件符合執行的語句 
} 
else{
    當條件不符合執行的語句 
}

2.例子

#include <iostream>
using namespace std;
int main(){
    int a;
    a = 20;
    if(a < 10){
        cout << "a小於10";
    }
    else{
        cout << "a大於10";
    }
}

輸出:

a大於10

3.例題

描述:

輸入一個數a

如果a是3的倍數,輸出"yes"

如果a不是3的倍數,輸出"no"

代碼:

#include <iostream>
using namespace std;
int main(){
    int a;
    cin >> a;
    if(a%3 == 0){
        cout << "yes";
    }
    else{
        cout << "no";
    }
}

 


免責聲明!

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



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