Menu
CoddyTech

逻辑运算符

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

Luau 的逻辑运算符会返回其中一个操作数,因此 5 and 9 的结果是 9,而 x or fallback 会选择一个默认值。C 的 && 和 || 也会以同样的方式短路,但会生成一个等于 0 或 1 的 int,而 C 用 ! 表示 not。用先求值的条件保护有风险的操作。比较时使用 ==:Luau 不允许在条件中赋值,但 C 接受 if (x = 0) 并会执行赋值。

Luau

local a, b = 5, 9
print(a and b)

C17

#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 的逻辑运算符,而不是 Luau 风格的操作数选择。

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

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

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

自己练习: C 在线编译器