比较运算符
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 22 课,共 94 课。
Dart 中的比较运算符会返回布尔值,这对做出决策至关重要。
void main() {
int a = 10;
int b = 10;
bool areEqual = a == b;
print('Is $a equal to $b? $areEqual');
}Dart 提供:相等(==)、不相等(!=)、大于(>)、小于(<)、大于或等于(>=),以及小于或等于(<=)。
挑战
入门创建一个程序,使用比较运算符比较两个游戏分数:
- 声明两个整数变量:
playerScore的值为 85,highScore的值为 90 - 使用比较运算符检查:
playerScore是否等于highScoreplayerScore是否不等于highScoreplayerScore是否大于 80playerScore是否小于highScoreplayerScore是否大于或等于 85playerScore是否小于或等于 100- 将每次比较的结果存储在一个名称具有描述性的布尔变量中
- 打印所有结果,并使用与预期输出完全一致的标签
输出必须符合以下格式:
Player score: 85 High score: 90 Scores are equal: false Scores are different: true Player score > 80: true Player score < High score: true Player score >= 85: true Player score <= 100: true
亲手试试
void main() {
// 在这里声明分数变量
int playerScore = ?;
int highScore = ?;
// 进行比较,并将结果存储在布尔变量中
bool scoresEqual = playerScore ? highScore;
bool scoresDifferent = playerScore ? highScore;
bool scoreAbove80 = playerScore ? 80;
bool scoreLessThanHigh = playerScore ? highScore;
bool scoreAtLeast85 = playerScore ? 85;
bool scoreAtMost100 = playerScore ? 100;
// 输出分数和比较结果
print("Player score: $playerScore");
print("High score: $highScore");
print("Scores are equal: $scoresEqual");
print("Scores are different: $scoresDifferent");
print("Player score > 80: $scoreAbove80");
print("Player score < High score: $scoreLessThanHigh");
print("Player score >= 85: $scoreAtLeast85");
print("Player score <= 100: $scoreAtMost100");
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Dart 在线编译器