[算术运算符]
说明
余数运算计算一个整数除以另一个整数时的余数。它对于将变量保持在特定范围内(例如数组的大小)很有用。 %
(百分比)符号用于执行余数运算。
用法
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
}
注意事项和警告
-
余数运算符不适用于浮点数。
-
如果第一个操作数为负,则结果为负(或零)。因此,如果
x
可以为负,x % 10
的结果将不会总是介于 0 和 9 之间。
相关用法
- Arduino %=用法及代码示例
- Arduino long用法及代码示例
- Arduino Arduino_EMBRYO_2 - setLengthXY()用法及代码示例
- Arduino ~用法及代码示例
- Arduino ArduinoBLE - bleDevice.advertisedServiceUuidCount()用法及代码示例
- Arduino const用法及代码示例
- Arduino Ethernet - server.begin()用法及代码示例
- Arduino ArduinoBLE - BLEService()用法及代码示例
- Arduino digitalWrite()用法及代码示例
- Arduino ArduinoBLE - bleCharacteristic.subscribe()用法及代码示例
- Arduino Servo - attach()用法及代码示例
- Arduino write()用法及代码示例
- Arduino Arduino_LSM9DS1 - readGyroscope()用法及代码示例
- Arduino ArduinoSound - FFTAnalyzer.input()用法及代码示例
- Arduino MKRGSM - gprs.attachGPRS()用法及代码示例
- Arduino WiFiNINA - WiFi.config()用法及代码示例
- Arduino MKRGSM - sms.read()用法及代码示例
- Arduino MKRNB - getCurrentCarrier()用法及代码示例
- Arduino Scheduler - Scheduler.startLoop()用法及代码示例
- Arduino Arduino_LSM9DS1 - magneticFieldAvailable()用法及代码示例
- Arduino MKRWAN - available()用法及代码示例
- Arduino ArduinoBLE - BLE.poll()用法及代码示例
- Arduino ArduinoBLE - bleCharacteristic.hasDescriptor()用法及代码示例
- Arduino Ethernet - EthernetUDP.parsePacket()用法及代码示例
- Arduino WiFi101 - WiFi.subnetMask()用法及代码示例
注:本文由纯净天空筛选整理自arduino.cc大神的英文原创作品 %。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。