C++-if语句

语法

  • C++ 中 if…else 语句的语法:
if(boolean_expression)
{
   // 如果布尔表达式为真将执行的语句
}
else
{
   // 如果布尔表达式为假将执行的语句
}

如果布尔表达式为 true,则执行 if 块内的代码。如果布尔表达式为 false,则执行 else 块内的代码。

流程图

在这里插入图片描述

实例
#include<iostream>
#include<string>
using namespace std;
int main() {
	//If-Then-Else
	/*
	int i;
	cin >> i;
	if (i <= 5)
		cout << "小于5" << endl;
	else
		cout << "大于5" << endl;
	*/

	//嵌套if语句
	int month, year;
	cout << "year= " << endl;
	cin >> year;
	cout << "month= " << endl;
	cin >> month;
	if ((year % 4 == 0 & year % 100 != 0) | year % 400 == 0)
		if (month == 2) {
			cout << "这个月有29天" << endl;
			switch (month) {
			case {1, 3, 5, 7, 8, 10, 12} :
				cout << "这个月有31天" << endl;
			case {4, 6, 9, 11}:
				cout << "这个月有30天" << endl;
			}
		}
		else
			cout << "这个月有28天" << endl;
	system("pause");
	return 0;
}
实战“闰年算法”
#include<iostream>
using namespace std;

int main() {
	int year;
	cout << "Enter a year:" << endl;
	cin >> year;
	if (year % 400 == 0)
		cout << "是闰年" << endl;
	if ((year % 4 == 0)&(year % 100 != 0))
		cout << "是闰年" << endl;
	else
		cout << "不是闰年" << endl;
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值