【问题标题】:How to get the difference between two integers如何获得两个整数之间的差
【发布时间】:2016-06-28 14:08:15
【问题描述】:

我正在尝试制作一个使用区域的程序,并且每个区域都有一个 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);

那么我怎样才能做到这一点呢?

【问题讨论】:

  • compareTo 始终返回 -1、0 或 1,具体取决于所需的两个对象的顺序。不确定我是否理解这个问题,但您可能想改用Math.abs(pos2.x - pos1.x) 之类的方法。

标签: java math compare


【解决方案1】:

compareTo 不应该返回两个值之间的确切差异。来自the docs

返回负整数、零或正整数,因为此对象小于、等于或大于指定对象。

使用

int x = Math.abs(pos2.x-pos1.x);
int y = Math.abs(pos2.y-pos1.y);
int size = x * y;

【讨论】:

  • 谢谢!仅供参考,在第二行“匹配”是错误的..正确的单词/类是“数学”
【解决方案2】:

结果为 1,因为 compareTo() 如果参数相等则返回 0,如果第一个 int 小于第二个,则返回 -1,如果第二个更小则返回 1(您可以在 @987654321 中了解更多信息@)。

--> 您不应该为此目的使用此方法。而是计算差异:

int x = pos2.x - pos1.x;
int y = pos2.y - pos1.y;
int size = Math.abs(x * y);

【讨论】:

    【解决方案3】:

    Integer.compareTo() 的目的不是求两个 Integer 对象之间的差异。其目的是指定两个 Integer 对象在通过 Arrays.sort() 或 Collections.sort() 排序时的顺序。

    您可以通过以下方式发现差异:

    int x = pos2.x - pos1.x;
    int y = pos2.y - pos1.y;
    int size = Math.abs(x * y);
    

    【讨论】:

      【解决方案4】:

      如果pos2.x 小于pos1.ycompareTo 将返回-1,如果它们相同,则返回0,如果pos2.x 大于pos1.y,则返回1

      改用这个:

      int size = Math.abs((pos2.x-pos1.x)*(pos2.y-pos1.y));
      

      【讨论】:

      • 那我可以用什么?
      • 如果你想要某个区域的尺寸,你可以用 pos1.x 减去 pos2.x,用 pos1.y 减去 pos2.y。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多