布尔值与分支
Coddy 面向 Kotlin 开发者的 C 课程的第 7 课,共 48 课。
Kotlin 的条件必须是 Boolean:对于 String?,if (s) 无法编译,因此你要写 s != null、s.isEmpty() 或 s.isNullOrEmpty()。C 可以将任何标量用作条件,指向空字符串的指针不为 null,因此会被视为 true。
零和 null 指针在条件中为 false。指向空字符串的指针仍然不为 null;要检测字符串是否为空,请检查它的第一个字节 s[0] == '\0'。
Kotlin 示例
fun main() {
val s: String? = ""
println(s != null)
println(s.isNullOrEmpty())
}
Kotlin 输出:
true
trueC 示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
const char *s = "";
printf("%s\n", s ? "true" : "false");
printf("%s\n", s[0] == '\0' ? "true" : "false");
return 0;
}
C 输出:
true
true挑战
简单输入为负数时返回 -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;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 C中的所有课
自己练习: C 在线编译器