逻辑或
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 24 课,共 94 课。
逻辑或运算符(||)会在至少一个表达式为 true 时返回 true,只有两个表达式都为 false 时才返回 false。
void main() {
bool hasCreditCard = false;
bool hasDebitCard = true;
bool canPayOnline = hasCreditCard || hasDebitCard;
print('Can this person pay online? $canPayOnline');
}输出:Can this person pay online? true
void main() {
int age = 16;
bool hasParentalConsent = true;
bool canWatchMovie = (age >= 18) || (age >= 13 && hasParentalConsent);
print('Can watch the movie? $canWatchMovie');
}挑战
入门使用逻辑 OR(||)运算符创建游戏资格检查器:
- 声明一个值为 15 的整数变量
age - 声明一个值为 true 的布尔变量
hasParentalConsent - 声明一个布尔变量
canPlayGame,用于检查以下条件是否至少满足一个: - 此人已满 18 岁(age >= 18),或者
- 此人已获得家长同意(hasParentalConsent 为 true)
- 按以下确切格式输出结果:
Age: 15
Has parental consent: true
Can play game: true然后将 hasParentalConsent 改为 false,并按相同格式输出更新后的结果。
亲手试试
void main() {
// 在这里声明你的变量
// 将每个占位值替换为任务描述的值
int age = 0;
bool hasParentalConsent = false;
// 检查此人是否可以玩游戏
bool canPlayGame = age >= 0 || hasParentalConsent;
// 打印初始结果
print("Age: $age");
print("Has parental consent: $hasParentalConsent");
print("Can play game: $canPlayGame");
// 更改家长同意状态
hasParentalConsent = true;
canPlayGame = age >= 0 || hasParentalConsent;
// 打印更新后的结果
print("\nAge: $age");
print("Has parental consent: $hasParentalConsent");
print("Can play game: $canPlayGame");
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Dart 在线编译器