Menu
CoddyTech

逻辑运算符

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

Kotlin 的 && 和 || 只接受 Boolean 操作数,并且会进行短路求值。中缀运算符 and 和 or 则不同:用于 Boolean 时,它们会计算两侧的表达式;用于 Int 时,它们是位运算符。C 的 && 和 || 接受任意标量,会对第二个操作数进行短路求值,并产生 int 类型的 0 或 1。

逻辑运算符会进行短路求值,并产生 0 或 1,而不是选择任意操作数的值。单字符运算符 & 和 | 是位运算符,类似于 Kotlin 中用于 Int 的 and 和 or。

Kotlin 示例

fun main() {
    val a = 6
    val b = 3
    println(a != 0 && b != 0)
    println(a and b)
}

Kotlin 输出:

true
2

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 = 6, b = 3;
    printf("%d %d\n", a && b, a & b);
    return 0;
}

C 输出:

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

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

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

自己练习: C 在线编译器