Java中的整数除法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37795248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:41:49  来源:igfitidea点击:

Integer division in Java

javamathintdivision

提问by MadMonty

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/doublesfirst, divided, then cast back to an integer, or is the division "done" as integers?

这感觉像是一个愚蠢的问题,但我在 Java 文档的任何地方都找不到答案。如果我声明两个整数然后将它们分开,到底发生了什么?它们是floats/doubles先转换为先分割,然后再转换回 an integer,还是作为整数“完成”?

Also, purely from experimentation, integer division seems to round the answer towards zero (i.e. 3/2 = 1and -3/2 = -1). Am I right in believing this?

此外,纯粹从实验来看,整数除法似乎将答案四舍五入到零(即3/2 = 1-3/2 = -1)。我相信这个正确吗?

采纳答案by Andrei Bardyshev

They are being divided in integer arithmetics. So dividing integer aby integer byou get how many times bfits into a. Also a % bwill give you a remainder of a division. So (a / b ) * b + a % b = a

它们在整数算术中被划分。因此,将整数除以整数ab您将得到b适合a. 同时a % b会给你一个除法的余数。所以(a / b ) * b + a % b = a

回答by Simon Kirsten

Java does autoconvert types:

Java 会自动转换类型:

"It autoconverts ints to doubles. It autoconverts shorts and bytes to ints even when no ints are involved, requiring constant annoying casts when you want to do short or byte arithmetic. It autoconverts primitives to wrappers and vice versa for boxing and autoboxing." - user2357112

“它自动将整数转换为双精度数。即使不涉及整数,它也会自动将短整数和字节转换为整数,当你想要进行短整数或字节算术时,需要不断进行烦人的转换。它自动将原语转换为包装器,反之亦然,用于装箱和自动装箱。” - 用户2357112

Java nevercasts anything without you specifying it.

如果没有您指定,Java永远不会强制转换任何内容。

But still integer / integer = integer.

但还是integer / integer = integer

Also, it does always truncate the result. So if the result would be 0.999999 as float the integer division would still return 0.

此外,它总是会截断结果。因此,如果结果为 0.999999 作为浮点数,整数除法仍将返回 0。