Menu
CoddyTech

剰余演算子

CoddyのDartジャーニー「基礎」セクションの一部。レッスン 18/94。

剰余演算子(%)を使うと、割り算の余りを求められます。簡単な例を使って、どのように動作するのか見てみましょう。

基本的な剰余演算

void main() {
  int dividend = 10;
  int divisor = 3;
  int remainder = dividend % divisor;
  
  print('Remainder of $dividend ÷ $divisor = $remainder');
}

出力: Remainder of 10 ÷ 3 = 1

10を3で割ると、商は3で余りは1です。剰余演算子%は、その余りの値を取得します。

偶数と奇数の判定

剰余演算子を使って、数値が偶数か奇数かを判定できます。

void main() {
  int number = 15;
  int remainder = number % 2;
  
  print('$number % 2 = $remainder');
  
  // 偶数を2で割った余りは0になる
  bool isEven = remainder == 0;
  
  // if/elseの代わりに真偽値を直接評価する
  String result = isEven ? '$number is even' : '$number is odd';
  print(result);
}

出力:

15 % 2 = 1
15 is odd
challenge icon

チャレンジ

簡単

剰余演算子(%)を使って、次の問題を解くプログラムを作成しましょう。

  1. 値が197の整数変数 totalMinutes を宣言します
  2. 整数除算を使って、totalMinutes に含まれる完全な時間数を計算して格納します
  3. 剰余演算子を使って、残りの分数を計算して格納します
  4. 次の形式と完全に同じ形式で、時間と分を出力します。
197 minutes is 3 hours and 17 minutes.

続いて:

  1. 値が57の整数変数 coins を宣言します
  2. coins から何枚の25セント硬貨を作れるか計算して格納します
  3. 剰余演算子を使って、残りの硬貨の枚数を計算して格納します
  4. 次の形式と完全に同じ形式で結果を出力します。
57 coins can be divided into 2 quarters and 7 remaining coins.

自分で試してみよう

void main() {
  // ここで変数を宣言してください
  // 以下の仮の値をすべて、課題で指定された値に置き換えてください
  int totalMinutes = 0;

  // 時間と残りの分を計算してください
  // 時間には整数除算を、分には剰余演算子を使ってください
  int hours = totalMinutes;
  int remainingMinutes = totalMinutes;

  // 時間の結果を出力してください
  print("$totalMinutes minutes is $hours hours and $remainingMinutes minutes.");

  // 25セント硬貨の枚数と残りの硬貨の枚数を計算してください
  int coins = 0;
  int quarters = coins ~/ 1;
  int remainingCoins = coins % 1;

  // 硬貨の結果を出力してください
  print("$coins coins can be divided into $quarters quarters and $remainingCoins remaining coins.");
}
quiz icon腕試し

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

基礎のすべてのレッスン

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