Dart 切り捨て除算を行う

Dart 切り捨て除算を行う

Dartで、切り捨て除算を行うコードを記述してます。対象の数値に「 remainder 」を使用することで可能です。

環境

  • OS windows11 home
  • Dart 2.18.4

切り捨て除算を行う

切り捨て除算を行うには、「 remainder 」を使用します。

数値.remainder(数値)

実際に、使用してみます。

void main() {
  print(10.remainder(3)); // 1
  print(5.remainder(3)); // 2
  print(-10.remainder(3)); // -1
  print(-5.remainder(3)); // -2
  print(10.remainder(-3)); // 1
  print(-10.remainder(-3)); // -1
}

実行結果を見ると、取得されていることが確認できます。

0を使用

「0」に使用するとエラーが発生します。

void main() {
  print(10.remainder(0));
  
  Unhandled exception:
IntegerDivisionByZeroException
#0      int.~/ (dart:core-patch/integers.dart:30:7)
#1      int._remainderFromInteger (dart:core-patch/integers.dart:116:43)
#2      int.remainder (dart:core-patch/integers.dart:77:18)
#3      main (file:///c:/sample/main.dart:2:12)
#4      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#5      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
}

数値以外

数値以外を指定するとエラーが発生します。

void main() {
  print('10'.remainder(10));
  
  Error: The method 'remainder' isn't defined for the class 'String'.
Try correcting the name to the name of an existing method, or defining a method named 'remainder'.
}