abs()

Last revision:2025/04/26

名称

abs()

説明

与えられた数値の絶対値を計算する。

書式

xの絶対値を計算するには、以下の関数を使う。

abs(x);

引数

この関数は以下の引数を受け付ける。

x数値

戻り値

xxが0以上のとき
-xxが0より小さいとき

コード例

変数xの絶対値をシリアルモニタに表示する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;  // wait for serial port to connect. Needed for native USB port only
  }
  int x = 42;
  Serial.print("The absolute value of ");
  Serial.print(x);
  Serial.print(" is ");
  Serial.println(abs(x));
  x = -42;
  Serial.print("The absolute value of ");
  Serial.print(x);
  Serial.print(" is ");
  Serial.println(abs(x));
}

void loop() {
}

注意

abs()はマクロとして実装されているため、引数に他の関数を使わないようにすること。そのような使い方をすると、意図しない結果になることがある。

1
2
3
4
5
abs(a++); // avoid this - yields incorrect results

// use this instead:
abs(a);
a++;  // keep other math outside the function

参照

オリジナルのページ

https://docs.arduino.cc/language-reference/en/functions/math/abs/

実装の解析

まだ解析していません。

最終更新日

July 12, 2026

inserted by FC2 system