【问题标题】:Possible lossy conversion from double to int从 double 到 int 的可能有损转换
【发布时间】:2014-12-12 08:14:19
【问题描述】:

为什么我会收到 Possible lossy conversion from double to int 错误,我该如何解决?

public class BinSearch {
    public static void main(String [] args)
    {
        double set[] = {-3,10,5,24,45.3,10.5};
        double l = set.length;
        double i, j, first, temp;
        System.out.print("Before it can be searched, this set of numbers must be sorted: ");
        for (i = l-1; i>0; i--)
        {
            first=0;
            for(j=1; j<=i; j++)
            {
                if(set[j] < set[first]) // location of error according to compiler
                {
                    first = j;
                }
                temp = set[first];
                set[first] = set[i];
                set[i] = temp;
            }
        }
    } 
}

如您所见,我已经尝试在声明变量时将int 替换为靠近顶部的double,但它似乎不起作用。

【问题讨论】:

  • 当您的double(例如3.141)用于访问数组索引时,您认为会发生什么?
  • 说实话,我真的不知道:/。

标签: java int double type-conversion


【解决方案1】:

将所有用作数组索引的变量从 double 更改为 int(即变量 jfirsti)。数组索引是整数。

【讨论】:

  • 所以我将l = set.length;i, j, first, temp; 的数据类型更改为int,但保持double 数据类型不变。它现在将temp = set[first]; 突出显示为有损转换错误。
  • @TigerLvr temp 应该保持双精度,因为您从双精度数组中为其分配值。
  • 我明白了。我还想知道,如果您不介意回答这个问题,为什么在尝试使用System.out.print("Before it can be searched, this set of numbers must be sorted: "); for(i=0; i&lt;1; i++) { System.out.print(" " + set[i]); } 打印未排序的数组时会导致输出为-3.0 而不是-3,10,5,24,45.3,10.5
  • @TigerLvr 你确定你试过的代码吗?我尝试了类似的代码并得到了-3.0 10.0 5.0 24.0 45.3 10.5?
  • 我确定。你能告诉我你把那部分代码放在哪里吗?
【解决方案2】:

数组/循环索引应该是整数,而不是双精度数。

例如,当尝试访问 set[j] 时,它抱怨将 j 视为 int。

【讨论】:

    【解决方案3】:

    如下更改变量类型。数组索引必须是 int 类型。

    public class BinSearch {
          public static void main(String [] args)
          {
              double set[] = {-3,10,5,24,45.3,10.5};
              int l = set.length;
              double temp;
              int i, j, first;
              System.out.print("Before it can be searched, this set of numbers must be sorted: ");
              for ( i = l-1; i>0; i--)
              {
                  first=0;
                  for(j=1; j<=i; j++)
              {
                  if(set[j] < set[first])//location of error according to compiler
                  {
                      first = j;
                  }
                  temp = set[first];
                  set[first] = set[i];
                  set[i] = temp;
              }
          }
      } 
    }
    

    【讨论】:

    • 谢谢。它似乎已经停止了错误。您介意向我解释一下为什么将 temp 设为双精度会阻止错误发生吗?
    • “set”的数据类型是double(64位值)。当您将其分配给类型为 int(32 位)的 temp 时,类型正在缩小。这不是隐含的可能。你可以像这样明确地做到这一点: temp = (int )set[first];或者,将 temp 的类型更改为 double,以便它可以接受 double 值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2015-02-28
    • 2014-08-02
    相关资源
    最近更新 更多