% (remainder)

説明

Remainder演算は、ある整数を別の整数で割ったときの余りを計算するものです。ある変数を特定の範囲(配列の大きさなど)に収めるのに便利です。余剰演算を実行するには、%(パーセント)記号を使用します。

構文

remainder = dividend % divisor;

remainder:変数。許容されるデータ型:int、float、double。
配当:変数または定数。許可されたデータ型:int。
除数:ゼロでない変数または定数。許可されたデータ型: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
}

注意点と警告

剰余演算子は浮動小数点数には作用しません。

最初のオペランドが負の場合、結果は負(またはゼロ)になります。したがって、x が負の値になる可能性がある場合、x % 10 の結果は 0 と 9 の間になるとは限りません。

タイトルとURLをコピーしました