%

[Arithmetic Operators]

説明

剰余演算は、ある整数を別の整数で割ったときの剰余を計算します。これは、変数を特定の範囲(例えば配列のサイズ)内に収めるのに便利です。剰余演算には、%(パーセント)記号が使用されます。

構文

remainder = dividend % divisor;

媒介変数

remainder: 変数。許可されるデータ型: intfloatdouble.
dividend: 変数または定数。許可されるデータ型: int.
divisornon zero 変数または定数。許可されるデータ型: int.

int x = 0;
x = 7 % 5;  // x now contains 2
x = 9 % 5;  // x now contains 4
x = 5 % 5;  // x now contains 0
x = 4 % 5;  // x now contains 4
x = -4 % 5; // x now contains -4
x = 4 % -5; // x now contains 4
/* update one value in an array each time through a loop */

int values[10];
int i = 0;

void setup() {}

void loop() {
  values[i] = analogRead(0);
  i = (i + 1) % 10; // remainder operator rolls over variable
}

ヒント

  1. 剰余演算子は浮動小数点数では機能しません。
  2. 最初のオペランドが負の場合、結果は負(またはゼロ)になります。したがって、x が負になる場合、x % 10 の結果は常に 0 から 9 の間になるとは限りません。

Language Reference Home

86Duinoリファレンスのテキストは、Arduinoリファレンスを改変したもので、Creative Commons Attribution-ShareAlike 3.0ライセンスに基づいてライセンスされています。リファレンス内のコードサンプルはパブリックドメインとして公開されています。

上部へスクロール