当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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大神的英文原创作品 %。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。