Java 从 double 到 int 的可能有损转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26413265/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:26:54  来源:igfitidea点击:

Possible lossy conversion from double to int

javaintdoubletype-conversion

提问by TigerLvr

Why am I getting the Possible lossy conversion from double to interror and how can I fix it?

为什么我会收到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;
            }
        }
    } 
}

As you can see, I've already tried replacing intwith doublenear the top when declaring variables but it doesn't seem to do the job.

如您所见,在声明变量时,我已经尝试将其替换intdouble接近顶部,但它似乎并没有完成这项工作。

采纳答案by Eran

Change all your variables used as array indices from double to int (i.e. the variables j, first, i). Array indices are integer.

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

回答by toolkit

The array / loop indexes should be ints, not doubles.

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

When attempting to access set[j]for example, it complains about treating j as an int.

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

回答by Manish Maheshwari

Change the variable types as below. Array indices must be of type int.

如下更改变量类型。数组索引必须是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;
          }
      }
  } 
}