%

名称

%

説明

整数同士の割り算での、剰余(余り)を計算する。配列の大きさなど、変数をある範囲内(例: 配列の大きさ)に収めるのに有用である。

書式

remainder = dividend % divisor;

引数

reminder変数。利用できるデータ型: int、float、double。
dividend変数もしくは定数。利用できるデータ型: int。
divisor非ゼロの変数もしくは定数。利用できるデータ型: int。

使用例

1
2
3
4
5
6
7
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/* 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. 一番目の引数が負の場合は、結果は負もしくは0である。このため、x % 10の結果は、xが負の場合も考えられるので、必ず0から9の間というわけではない。

参照

オリジナルのページ

https://www.arduino.cc/reference/en/language/structure/arithmetic-operators/multiplication/

Last Revision: 2019/02/21

最終更新日

January 4, 2024

inserted by FC2 system