Java中的整数除法 [英] Integer division in Java

查看:127
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆