布尔值与分支
Coddy 面向 Ruby 开发者的 C 课程的第 7 课,共 48 课。
Ruby 只将 nil 和 false 视为假值,因此 0 和空字符串都是真值,检查是否为空要用 empty?。在 C 中,标量零为假,非零标量为真,因此 0 的含义正好相反;非空指针为真,即使它指向空字符串也是如此。需要明确的布尔结果时,可以使用 stdbool.h 中的 bool。
Ruby
n = 0
s = ""
puts "#{n ? true : false} #{s ? true : false}"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 n=0; const char *s=""; printf("%s %s\n",n?"true":"false",s?"true":"false");
return 0;
}
移植规则
需要判断是否为空时,检查内容或长度;不要只检查指针。
挑战
简单输入为负数时返回 -1,输入为 0 时返回 0,输入为正数时返回 1。
编辑未锁定的源文件和头文件。确保声明的公共 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 n=0;if(scanf("%d",&n)!=1)return 1;printf("%d\n",sign_of(n));return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C中的所有课
自己练习: C 在线编译器