Menu
CoddyTech

逻辑运算符

Coddy 面向 Swift 开发者的 C 课程的第 8 课,共 48 课。

Swift 的 && 和 || 只接受 Bool 操作数,并返回 Bool。右侧操作数是自动闭包,只会在需要时运行。C 接受任意标量操作数,并返回 int,即 0 或 1。两者都会短路,因此第一个测试可以保护第二个可能有危险的操作。

逻辑运算符会短路,并产生 0 或 1,而不是选择任意操作数的值。

Swift 示例

print(5 != 0 && 9 != 0)

Swift 输出:

true

C 示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
int a=5, b=9; printf("%d\n",a && b);
return 0;
}

C 输出:

1
challenge icon

挑战

简单

输入为被除数 a 和除数 b。仅当 b 不为零且 a 能被 b 整除时返回 1,否则返回 0。b 为零时,绝不要计算 a%b。

编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查取值范围,否则所有数值任务测试数据都足够小,不会导致溢出。只打印指定的输出;如果给出了驱动程序,它会负责解析输入并生成输出。

亲手试试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int a=0,b=0;if(scanf("%d%d",&a,&b)!=2)return 1;printf("%d\n",divides(a,b));return 0;}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Swift 开发者的 C中的所有课

自己练习: C 在线编译器