逻辑运算符
Coddy 面向 Python 开发者的 C 课程的第 8 课,共 48 课。
Python 的 and/or 会返回操作数。C 的 && 和 || 会进行短路求值,但会生成等于 0 或 1 的 int。先用一个会优先求值的条件保护有风险的操作。比较时使用 ==,不要用赋值。
Python
print(5 and 9)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) {
printf("%d\n",5 && 9);
return 0;
}
移植规则
要得到真值结果,请使用 C 的逻辑运算符,而不是像 Python 那样选择操作数。
挑战
简单输入是分子 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;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 C中的所有课
自己练习: C 在线编译器