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