title: 261107周六下午 - else子句与逻辑语句 author: wu_sir date: 2026-11-07 organization: 河源高级中学 & 河源市中小学科普教育馆 header: title————{title} ———— {author}(organization)footer:起始于:{organization}) footer: 起始于:{date} - - - - - - 第 pageNo页/共{pageNo} 页 / 共 {pageCount} 页 - - - - - - 终止于:${today} keywords:

  • else
  • 逻辑语句

else子句

#B1036. 三个数排序(数据加强版)

codes
	int a, b, c;
	cin >> a >> b >> c;
	
	if(a < b) {	// c  a  c  b  c 
		if(c < a) cout << c << ' ' << a << ' ' << b;
		else if(c < b) cout << a << ' ' << c << ' ' << b;
		else cout << a << ' ' << b << ' ' << c;
	} else {	// c  b  c  a  c
		if(c < b) cout << c << ' ' << b << ' ' << a;
		else if(c < a) cout << b << ' ' << c << ' ' << a;
		else cout << b << ' ' << a << ' ' << c;
	}

#B1105. 简单计算器

code
	int a, b;
	char c;
	cin >> a >> c >> b;
	
	if(c == '+') cout << a + b;
	else if(c == '-') cout << a - b;
	else if(c == '*') cout << a * b;
	else if(c == '/') {
		if(b != 0) cout << a / b;
		else cout << "Divided by zero!";
	} else cout << "Invalid operator!";

#B1107. 判断点在第几象限

code
	int x, y;
	cin >> x >> y;
	
	if(x > 0) {
		if(y > 0) cout << 1;
		else cout << 4;
	} else {
		if(?) ...;
	}

逻辑运算

#B1108. 同时被 3 和 5 整除

思路
  • 当前这个场景,直接用 if-else 也是可以解决的,但问题在于太麻烦

  • 需要同时判定能够整除 3 和 5

  • 复合两个判定语句,通过【逻辑运算】

    • 三个基本的逻辑运算:并且、或者、不是
    • 与、或、非
    • &&、||、!
    • and、or、not
  • 	int n;	cin >> n;
    	if(n % 3 == 0 && n % 5 == 0) cout << "true";
    	else cout << "false";
    

#B1112. 点和矩形的关系

code
	int x1, y1, x2, y2;
	cin >> x1 >> y1 >> x2 >> y2;
	int ax, ay;
	cin >> ax >> ay;
	
	if(ax < x1 || ax > x2 || ay < y1 || ay > y2) cout << "outside";
	// else if(ax == x1 || ax == x2 || ay == y1 || ay == y2) cout << "on";
	// else cout << "inside";
	else if(ax > x1 && ax < x2 && ay > y1 && ay < y2) cout << "inside";
	else cout << "on";

#B1115. 判断闰年

并且运算的优先级高于或者运算。

#B1027. 线段相交

code
	int a, b, c, d;
	cin >> a >> b >> c >> d;
	// 取两个左端点的较大值,和两个右端点的较小值
	// 如果其左端点小于右端点,那么这个区间就是相交的部分,否则说明不相交
	if(c > a) a = c;	// 认为 a 就是 ac 中较大值,如果 c 超过 a,那么更新 a
	if(d < b) b = d;	// 同上
	// 此时 [a, b] 就是相交的部分
	if(a < b) cout << b - a;
	else cout << 0;

循环结构

  • 三大基本结构

    • 顺序结构:从上往下
    • 分支结构:可以允许执行或者选择不执行某些语句
    • 循环结构:能够提供大量的逻辑
  • 用少量的代码执行很多的逻辑(语句)

    • 循环结构

    • while(逻辑语句 A) {
        如果逻辑语句 A 成立就执行;
      }
      
      

#B1118. 输出 1 ~ n

code
    int n;  cin >> n;
    // 输出 1 - n 的所有整数
    int i = 1;  // 循环变量:其作用为【控制循环的运行】
    while(i <= n) {
        cout << i << ' ';
        i = i + 1;  // i += 1, i ++
    }

0 条评论

目前还没有评论...