[英]Arithmetic error in C function
int getTempo()
{
int tempo;
//User can enter tempo in bpm
tempo = (aserveGetControl(07) / 127) * 250;
//equation to convert tempo in bpm to an integer in ms to use with aserveSleep
return ((1000/tempo) * 60);
}
程序将无法通过该函数运行,并出现以下错误:线程1:EXC_ARITHMETIC(代码= EXC_I386_DIV,子代码= 0x0)
如果像我想的那样,如果aserveGetControl
返回一个0到127之间的整数,则tempo
将始终为零(除非aserveGetControl
返回恰好是127),因为您正在执行整数除法,这aserveGetControl
结果截断为整数部分。 您应该反转两个表达式的除法和乘法,并且无论如何都准备好处理aserveGetcontrol
可能返回0的事实。
使用整数数学时,应在除法之前进行乘法。
示例1(截断为零)
(100 / 127) * 250
= (0) * 250
= 0
另一方面
(100 * 256) / 127
= 25600 / 127
= 201
示例2(精度损失)
(1000 / 27) * 60
= (370) * 60
= 2220
另一方面
(1000 * 60) / 27
= (60000) / 127
= 2222
尝试这个:
int getTempo()
{
int tempo;
//User can enter tempo in bpm
tempo = (aserveGetControl(07) * 250) / 127;
//equation to convert tempo in bpm to an integer in ms to use with aserveSleep
return (60 * 1000) / tempo ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.