當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Arduino abs()用法及代碼示例

[數學]

說明

計算數字的絕對值。

用法

abs(x)

參數

x : 編號

返回

x: 如果 x 大於或等於 0。
-x: 如果 x 小於 0。

示例代碼

將變量x 的絕對值打印到串行監視器。

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()函數的實現方式,請避免使用括號內的其他函數,可能會導致結果不正確。

abs(a++); // avoid this - yields incorrect results

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

相關用法


注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 abs()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。