3.1 if语句

如果表达式1为true,后面的if 、else if 、else 语句将不再执行;

如果表达式1位false,执行表达式2,表达式2为true,后面的if 、else if 、else 语句将不再执行;

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
	int a;
	cin >> a;
	if( !(a%2) ) //!0==1 相当于 a%2==0 
	{
		cout << "偶数" << endl; 
	}
	else 
	{
		cout << "奇数" << endl; 
	} 
	return 0;
} 

【重点】else总是与离它最近的if配对,和是否与if对其没有关系。

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
	int year;
	cin >> year;
	if( year <= 0)
	{
		cout << "Illegal year." << endl;
	}
	else
	{
		cout << "Legal year." << endl;
		if( year > 1949 && (year - 1949) % 10 == 0)  
			cout << "Lucky year." << endl;
		else if( year > 1921 && !((year -1921) % 10))//相当于(year - 1921) % 10 == 0,!0为真->执行。 
			cout << "Good year." << endl;
		else if( year % 4 == 0 && year % 100 || year % 400 == 0)
			cout << "Leap year." << endl;
		else 
			cout << "Commen year." << endl;
	}
	return 0;
}

【重点】表示判断两个等号“==”

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/81006899
3.1