Java中的整数除法 [英] Integer division in Java
问题描述
这听起来像是一个愚蠢的问题,但是我在Java文档的任何地方都找不到答案.如果我声明两个int然后将它们除,则究竟发生了什么?是先将它们转换为floats/doubles
,除以然后再转换回integer
,还是将除法作为整数完成"?
This feels like a stupid question, but I can't find the answer anywhere in the Java documentation. If I declare two ints and then divide them, what exactly is happening? Are they converted to floats/doubles
first, divided, then cast back to an integer
, or is the division "done" as integers?
此外,纯粹从实验来看,整数除法似乎将答案舍入为零(即3/2 = 1
和-3/2 = -1
).我相信这一点对吗?
Also, purely from experimentation, integer division seems to round the answer towards zero (i.e. 3/2 = 1
and -3/2 = -1
). Am I right in believing this?
推荐答案
它们被划分为整数运算.因此,将整数a
除以整数b
可得到b
符合a
的次数.同样,a % b
将给您除法的余数.所以(a / b ) * b + a % b = a
They are being divided in integer arithmetics. So dividing integer a
by integer b
you get how many times b
fits into a
. Also a % b
will give you a remainder of a division. So (a / b ) * b + a % b = a
这篇关于Java中的整数除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!