Menu
CoddyTech

比較演算子

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には、等価(==)、不等価(!=)、より大きい(>)、より小さい(<)、以上(>=)、以下(<=)があります。

challenge icon

チャレンジ

初心者

比較演算子を使って、2つのゲームのスコアを比較するプログラムを作成しましょう。

  1. 整数変数を2つ宣言します。playerScore の値は85、highScore の値は90にします。
  2. 比較演算子を使って、次の条件を確認します。
    • playerScore が highScore と等しいか
    • playerScore が highScore と等しくないか
    • playerScore が80より大きいか
    • playerScore が highScore より小さいか
    • playerScore が85以上か
    • playerScore が100以下か
  3. 各比較結果を、内容がわかる名前のブール変数に保存します。
  4. 期待される出力に示されているラベルをそのまま使い、すべての結果を出力します。

出力は次の形式と完全に一致する必要があります。

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");
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

基礎のすべてのレッスン

自分で練習してみよう: Dartオンラインコンパイラ