[Arithmetic Operators]
説明
剰余演算は、ある整数を別の整数で割ったときの剰余を計算します。これは、変数を特定の範囲(例えば配列のサイズ)内に収めるのに便利です。剰余演算には、%(パーセント)記号が使用されます。
構文
remainder = dividend % divisor;
媒介変数
remainder: 変数。許可されるデータ型: int, float, double.dividend: 変数または定数。許可されるデータ型: int.divisor: non 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
}ヒント
- 剰余演算子は浮動小数点数では機能しません。
- 最初のオペランドが負の場合、結果は負(またはゼロ)になります。したがって、
xが負になる場合、x % 10の結果は常に 0 から 9 の間になるとは限りません。
Language Reference Home
86Duinoリファレンスのテキストは、Arduinoリファレンスを改変したもので、Creative Commons Attribution-ShareAlike 3.0ライセンスに基づいてライセンスされています。リファレンス内のコードサンプルはパブリックドメインとして公開されています。