[英]Operator in Java like // in python?
Is there a form of the // operator that is used in python that I can use in java, or some sort of workaround?是否有可以在 java 中使用的在 python 中使用的 // 运算符的形式,或者某种解决方法? 10 // 3 = 3
10 // 3 = 3
In python 3 //
act as a floor division by default.在 python 3
//
默认情况下充当地板分区。
In python 2.2 and later 2.X version we can import it from the __future__
在 python 2.2 和更高版本的 2.X 版本中,我们可以从
__future__
导入它
>>> from __future__ import division
>>> 10/3
3.3333333333333335
>>> 10//3
3
In Java: When dividing floating-point variables or values, the fractional part of the answer is represented in the floating-point variable.在 Java 中:当除以浮点变量或值时,答案的小数部分在浮点变量中表示。
float f = 10.0f / 6.0f; // result is 1.6666
double d = 10.0 / 9.0; // result is 1.1111
But for floor in java:但是对于java中的地板:
(int)Math.floor(10/3);
public static int python_like_divisor(int x, int y) {
final remainder = x % y;
if(remainder != 0) {
return (x - remainder) / y;
}
return x / y;
}
Some basic math knowledge is good ;)一些基本的数学知识很好;)
With float-point (float, double etc.) values this method will not work properly.对于浮点(float、double 等)值,此方法将无法正常工作。
One thing to notice is:需要注意的一件事是:
in python 3:在python 3中:
6 // -132 = -1 6 // -132 = -1
in java:在java中:
6 / -132 = 0 6 / -132 = 0
Java's integer division will act in the same way as the // operator in Python. Java 的整数除法的作用与 Python 中的 // 运算符相同。 This means that something like this:
这意味着这样的事情:
(int) 9/4 == 2 is True
The cast here is even unnecessary because both 9 and 4 are integers.这里的强制转换甚至是不必要的,因为 9 和 4 都是整数。 If one was a float or a double this cast would be necessary as java would no longer execute this statement as integer division.
如果一个是浮点数或双精度数,则必须进行此转换,因为 java 将不再将此语句作为整数除法执行。 To be more explicit you could do this
更明确地说,你可以这样做
(int)Math.floor(9 / 4);
which divides the numbers first and then floors the results to the nearest integer.它首先将数字相除,然后将结果降到最接近的整数。
您可以使用java.lang.Math#floorDiv(int, int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.