循环中的数组可能会丢失精度错误

Mia*_*ich 5 arrays precision

所以我在一些程序中一直遇到类似的错误,我无法弄明白.循环中的数组和所有变量都是double,所以我不明白为什么它需要一个int值.无论如何,所有的错误都引用了最后一个块中的for语句:

 import java.util.Scanner;

    public class Exercise610
    { public static void main (String[] args)
        {
        int smallest;
        Scanner stdIn = new Scanner (System.in);
        double array1 [] = new double [100]; 
        for (int i=0; array1[i] != -7; i++)
        {
            System.out.println("Input a value in yer string, or -7 to end");
            array1[i] = stdIn.nextDouble();
        }

        smallest = indexOfSmallestElement(array1);
        System.out.println("The smallest value in the array is " + smallest);
    }


    public static int indexOfSmallestElement (double[] array)
    {
        int smallestInt;
        double smallest = array[0];
        for (double u: array)
        {
            if (array[u+1] < array[u])
            {
                smallest = array[u+1];
            }
        }
        smallestInt = (int) smallest;
        return smallestInt;
    }
}
Run Code Online (Sandbox Code Playgroud)

文件:/Users/Crbn/introcs/Exercise610.java [行:33]
错误:/Users/Crbn/introcs/Exercise610.java:33:可能的精度损失
发现:双
需要:INT
文件:/用户/ CRBN/introcs /Exercise610.java [行:33]
错误:/Users/Crbn/introcs/Exercise610.java:33:可能损失的精度
发现:双
所需:INT
文件:/Users/Crbn/introcs/Exercise610.java [行:35 ]
错误:/Users/Crbn/introcs/Exercise610.java:35:
发现可能的精度损失:double
required:int

Ḟḹá*_*ƀíé 4

您不能说,array[u+1]因为 this 指的是数组的索引。错误是因为 isu是一个double并且任何数组中的索引都是 0、1、2 等整数中的数字...

您应该使用整数循环遍历数组,例如:

for (int i = 0; i < something; i++){
    // do something here
}
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以转换u为 int (请参见下面的代码),但最好int首先声明它。

 for (double u : array) {
            if (array[(int) (u + 1)] < array[(int) u]) {
                smallest = array[(int) (u + 1)];
            }
        }
Run Code Online (Sandbox Code Playgroud)

造成精度误差损失的原因是因为 anint占用 32 位内存,adouble占用 64 位,因此如果尝试将 a 挤入doublean 中int,可能会丢失一些数据。