比較演算子
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 は、等価 (==)、非等価 (!=)、より大きい (>)、より小さい (<)、より大きいか等しい (>=)、より小さいか等しい (<=) を提供します。
チャレンジ
初心者比較演算子を使用して2つのゲームスコアを比較するプログラムを作成してください:
- 2つの整数変数を宣言してください:
playerScoreを85、highScoreを90に設定 - 比較演算子を使用して次のことをチェックしてください:
playerScoreがhighScoreと等しいかどうかplayerScoreがhighScoreと等しくないかどうかplayerScoreが80より大きいかどうかplayerScoreがhighScoreより小さいかどうかplayerScoreが85以上かどうかplayerScoreが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
チートシート
Dartの比較演算子は、意思決定のためにブール値を出力します:
==- 等しい!=- 等しくない>- より大きい<- より小さい>=- 以上<=- 以下
void main() {
int a = 10;
int b = 10;
bool areEqual = a == b;
print('Is $a equal to $b? $areEqual');
}自分で試してみよう
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");
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。