% (餘數運算子)

描述

計算整數除法中的餘數,它在維持一個變數的數值在一定範圍內時相當有用(例如一個陣列的大小)。

語法

result = dividend % divisor

參數

dividend: 被除數
divisor: 除數

回傳值

餘數

範例

x = 7 % 5;   // x 現在是 2
x = 9 % 5;   // x 現在是 4
x = 5 % 5;   // x 現在是 0
x = 4 % 5;   // x 現在是 4

範例草稿碼

/* 每次迴圈皆回傳不一樣的餘數數值 */

int values[10];
int i = 0;

void setup() {}

void loop()
{
  values[i] = analogRead(0);
  i = (i + 1) % 10;   // 透過 % 運算,i 這個變數值會介在 0 ~ 9 之間  
}

提醒

% 運算子不能用在浮點數運算上。

See also

division


語法參考主頁面

本頁由熱血青年 LBU 譯自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.