# AcWing | 语法基础课 | 判断语句

38 阅读2分钟

AcWing | 语法基础课 | 判断语句

printf函数应用

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int a = 1;
	int b = 23;
	int c = 456;
	
	printf("%5d!\n", a);
	printf("%5d!\n", b);
	printf("%5d!\n", c);
	
	return 0;
}

对于上面函数的应用,%5d代表占用五个字符空间,输出右对齐,%-5d代表左对齐。%05d代表占用五个字符空间,没占用的位置用0代替。

if函数

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int score;
	cin >> score;
	if (score >= 60)
	{
		cout << "及格"; 
	}
	else
	{
		cout << "不及格";
	}
	
	return 0;
}

else部分可以省略,对程序本身没有影响。在{}中只有一条语句时,{}可以省略。

/*
	大于 a > b
	小于 a < b
	大于等于 a >= b
	小于等于 a <= b
	等于 a == b
	不等于 a !=b 
	*/

if可以进行多种嵌套

最大值

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int a, b, c;
	cin >> a >> b >> c;
	if (a >= b)
	{
		if (a >= c)
		{
			cout << a << endl;
		}
		else
		{
			cout << c << endl;
		}
	}
	else
	{
		if(b >= c)
		{
			cout << b << endl;
		}
		else
		{
			cout << c << endl;
		}
	}
	return 0;
}

if-else 函数

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int grade;
	cin >> grade;
	if (grade >= 85) cout << 'A' << endl;
	else
	{
		if (grade >= 70) cout << 'B' << endl;
		else
		{
			if (grade >= 60) cout << 'C' << endl;
			else cout << 'D' << endl;
		}
	}
	return 0;
}

完全等价于

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int grade;
	cin >> grade;
	if (grade >= 85) cout << 'A' << endl;
	else if (grade >= 70) cout << 'B' << endl;
	else if (grade >= 60) cout << 'C' << endl;
	else cout << 'D' << endl;
	return 0;
}
#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int a, b, c;
	char x;
	scanf("%d %d %c", &a, &b, &x);
	if ( x == '+')
	{
		c = a+b;
		cout << c << endl;
	}
	else if ( x == '-')
	{
		c = a-b;
		cout << c << endl;
	}
	else if ( x == '/')
	{
		if(b==0)
		{
			cout << "Divided zero" << endl;	
		}
		else
		{
			c = a/b;
			cout << c << endl;
		}	
	}
	else if ( x == '*')
	{
		c = a*b;
		cout << c << endl;
	}
	else
	{
		cout << "Invalid operate" << endl;	
	}


	return 0;
}

判断闰年

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
	int a;
	cin >> a;
	if (a%100 == 0){
		if (a%400 == 0){
			cout << "Yes" << endl;
		}
		else{
			cout << "No" << endl;
		}
	}
	else{
		if(a%4==0){
			cout << "Yes" << endl;
		}
		else {
			cout << "No" << endl;
		}
	}

	return 0;
}

或与非

或 || 与 && 在判断语句中实现 可以进行嵌套 &&的优先级比||更高