Menu
CoddyTech

逻辑运算符

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

Dart 的 && 和 || 只接受 bool 操作数,并返回一个 bool,因此两个 int 值不能使用 a && b 编译,你需要编写显式比较。C 接受标量真值测试,并将结果规范化为整数 0 或 1。两者都会短路求值,不再计算第二个操作数。

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

Dart 示例

void main() {
  int a = 5, b = 9;
  print(a != 0 && b != 0);
}

Dart 输出:

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自我测试

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

面向 Dart 开发者的 C 语言课程中的所有课

自己练习: C 在线编译器