Java 如何求两个整数的差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38078503/
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
How to get the difference between two integers
提问by letsgo00
I'm trying to make a program which uses areas and each area has an id (e.g.:1;1) and I'm trying to get the size of a specified area with comparing two ids but this method returns 1 as size.
我正在尝试制作一个使用区域的程序,每个区域都有一个 id(例如:1;1),我试图通过比较两个 id 来获取指定区域的大小,但此方法返回 1 作为大小。
//Pos1 = -2;3 Pos2 = 0;1
int x = Integer.valueOf(pos2.x).compareTo(pos1.x);
int y = Integer.valueOf(pos2.y).compareTo(pos1.y);
int size = Math.abs(x * y);
So how can I make this work?
那么我怎样才能做到这一点呢?
采纳答案by Katharina
The result is 1 because compareTo()
returns 0 if the arguments are equal, -1 if the first int is smaller than the second one and 1 if the second one is smaller (you can read more about it in the official docs).
结果为 1,因为compareTo()
如果参数相等则返回 0,如果第一个 int 小于第二个则返回 -1,如果第二个更小则返回 1(您可以在官方文档中阅读更多相关信息)。
--> You should not use this method for this purpose. Calculate the difference instead:
--> 你不应该为此目的使用这个方法。计算差异:
int x = pos2.x - pos1.x;
int y = pos2.y - pos1.y;
int size = Math.abs(x * y);
回答by Shiro
compareTo
will return -1
if pos2.x
is smaller than pos1.y
, 0
if they are the same, and 1
if pos2.x
is greater than pos1.y
.
compareTo
将返回-1
ifpos2.x
小于pos1.y
,0
如果它们相同,并且1
ifpos2.x
大于pos1.y
。
Use this instead:
改用这个:
int size = Math.abs((pos2.x-pos1.x)*(pos2.y-pos1.y));
回答by f1sh
compareTo
is not supposed to return the exact difference between two values. From the docs:
compareTo
不应该返回两个值之间的确切差异。从文档:
Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
当此对象小于、等于或大于指定对象时,返回一个负整数、零或正整数。
Use
用
int x = Math.abs(pos2.x-pos1.x);
int y = Math.abs(pos2.y-pos1.y);
int size = x * y;
回答by Sanjeev Saha
Purpose of Integer.compareTo ( ) is not to find the difference between two Integer objects. Its purpose is to specify the ordering between two Integer objects when they are sorted by Arrays.sort ( ) or Collections.sort( ).
Integer.compareTo ( ) 的目的不是找出两个 Integer 对象之间的差异。其目的是指定两个 Integer 对象在按 Arrays.sort() 或 Collections.sort() 排序时之间的顺序。
You may find the difference in following ways:
您可以通过以下方式发现差异:
int x = pos2.x - pos1.x;
int y = pos2.y - pos1.y;
int size = Math.abs(x * y);