% (余数运算子)

描述

计算整数除法中的余数,它在维持一个变数的数值在一定范围内时相当有用(例如一个阵列的大小)。

语法

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.