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


Arduino %用法及代碼示例

[算術運算符]

說明

餘數運算計算一個整數除以另一個整數時的餘數。它對於將變量保持在特定範圍內(例如數組的大小)很有用。 %(百分比)符號用於執行餘數運算。

用法

remainder = dividend % divisor;

參數

remainder: 多變的。允許的數據類型:int,float,double.
dividend: 變量或常量。允許的數據類型:int.
divisor非零變量或常數。允許的數據類型: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
}

注意事項和警告

  1. 餘數運算符不適用於浮點數。

  2. 如果第一個操作數為負,則結果為負(或零)。因此,如果x 可以為負,x % 10 的結果將不會總是介於 0 和 9 之間。

相關用法


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