木之夏  
海纳百川,有容乃大;壁立千仞,无欲则刚

C++中if语句的使用

 

if语句的主要作用是进行分支的判断,通过判断表达式的真假进行选择支路

if语句

If语句的语法形式

if (表达式) 语句

例:if (x > y) cout << x;

if (表达式) 语句1 else 语句2

例:if (x > y) cout << x;

else cout << y;

if (表达式1) 语句1
else if (表达式2) 语句2
else if (表达式3) 语句3
           …
else 语句 

 

嵌套的if结构

 

l  语法形式

 

if(   )

 

if(   ) 语句 1

 

else 语句 2

 

else

 

if(   ) 语句 3

 

else 语句 4

 

l  注意

 

n  语句 1、2、3、4 可以是复合语句;

 

n  每层的 if 与 else 配对,或用 { } 来确定层次关系。

程序实例:

计算闰年的实例;

首先需要知道闰年的计算方法;

如果该年份的数字 可以被4整除并且可以被100整除  或 可以被400整除的都算做闰年:

程序实现;

#include <iostream>
using namespace std;

int main()
{
// 求解输入的年份是否为闰年
    int year;
    bool isLeapYear;


    cout<< "Please enter a year:"<<  '\n';
    cin >> year ;
    isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
    if (isLeapYear)
        cout << "the " << year <<" is a Leap Year";
    else
        cout << "the " << year << " is not a  Leap Year";

    return 0;
}

 

posted on 2021-02-13 07:58  木之夏  阅读(6421)  评论(0编辑  收藏  举报