布尔条件
Coddy 面向 Lua 开发者的 Dart 课程的第 7 课,共 48 课。
在 Lua 中,只有 nil 和 false 是假值,因此 0 和空字符串都算作真值,而且 and/or 会返回其中一个操作数,而不是布尔值。Dart 的条件和逻辑操作数必须是 bool。两者都会短路,因此被跳过的右侧操作数不会产生任何副作用。
条件和逻辑操作数必须是 bool。短路运算符的右侧只会在需要时运行,因此带有输出的回调可能会完全跳过。
完整的 Lua 程序:
local function probe()
print('probe')
return true
end
if false and probe() then
print('open')
else
print('closed')
end
完整的 Dart 程序:
bool probe(){print('probe');return true;}
void main(){if(false && probe()){print('open');}else{print('closed');}}挑战
简单实现 safe(int temperature, bool doorClosed):仅当温度在 10 到 80 之间(含两端),且门处于关闭状态时返回 true。输入是一个温度以及 true 或 false。返回小写的布尔文本。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后打印一个换行符。
你的代码应写在 functions.dart、exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(safe(40,true));check(!safe(40,false));
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Lua 开发者的 Dart中的所有课
自己练习: Dart 在线编译器