比較演算子
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
自分で試してみよう
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オンラインコンパイラ