如何摆脱除法运算符?
我应该写什么才能摆脱除法运算符,而不是写“/6”?
int a ;
c = a / 6 ;
如果您对这个主题了解更多,您能给我当 b != 2 的倍数时的通用算法吗?
例如:
b = 1, 3, 5, 6, 7, 9, 10 等
Instead of writing " / 6 ", what should I write so that I can get rid of division operator ?
int a ;
c = a / 6 ;
If you know more on that topic, can you give me general algorithm when b != multiple of 2 ?
ex :
b = 1, 3, 5, 6, 7, 9, 10 , etc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,移位和减法(将
/
替换为>>
和可选的-
的一般形式,通常用于 power-of -2 除数)是 int 的除法运算,所以我不确定您应该如何消除它。如果他们说用模数(%
)替换它,我会发现他们很难认真对待。对于float
或double
,您可以尝试乘以倒数(这会将除法移到编译时而不是运行时),只要您不丢失精度太高,但是对于不采用定点表示的整数类型来说,这会更棘手。Well, shift-and-subtract (the general form of replacing
/
with>>
and optionally-
, commonly seen for power-of-2 divisors) is what the division operation does for anint
, so I'm not sure how you'd be expected to eliminate it. If they say to replace it with modulus (%
), I'd find them hard to take seriously. Forfloat
ordouble
, you could try multiplication by the reciprocal (which moves the division into compile-time instead of run-time), so long as you don't lose too much precision, but that's trickier for integral types without resorting to fixed point representation.