语法
- 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;
}