布尔条件
Coddy 面向 Ruby 开发者的 Dart 课程的第 7 课,共 48 课。
Ruby 只把 nil 和 false 视为假;零和空字符串都为真。它的 && 和 || 会返回操作数的值,而 Dart 要求操作数为 bool,并且结果也是 bool。两者都会短路,因此右侧带有可见输出的调用可能会完全跳过。
条件和逻辑操作数必须是 bool。短路运算符的右侧只会在需要时运行,因此带有输出的回调可能会完全跳过。
完整的 Ruby 程序:
def probe
puts 'probe'
true
end
if false && probe
puts 'open'
else
puts '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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 Dart中的所有课
自己练习: Dart 在线编译器