不兼容的类型:使用Java中的Math.sqrt和Math.pow从Double到Int的可能的Loosy转换

时间:2016-06-29 17:20:37

标签: java oracle

我收到以下错误,我不知道为什么:(

Incompatible types: possible loosy conversion from double to int

它显示在代码的第109行。该代码使用Math.sqrt和Math.pow。

代码:

        total[b] = Math.sqrt( Math.pow( 2, ( x[b+1][b+1] - x[b][b+1] ) )  +  Math.pow( 2, ( x[b+2][b+2] - x[b][b+2] ) ) );

如果是一个简单的错误,请饶了我。我昨天刚刚开始使用Java,我正试图抓住它。我也是Stack Overflow的新成员:)

这是我的代码:

import java.util.Scanner;

public class twoDArray4 {

public static void main(String args[])
{
    int rows;
    int columns = 3;



    Scanner scan = new Scanner(System.in);

    System.out.print("Please enter the number of cities: ");
    rows = scan.nextInt();

    double x[][] = new double [rows][columns];

    String name[] = new String[rows];

    // --- Inputting ---


    // 1st City Column Starting from 1

    for (int k = 0; k < rows; k++)
    {
        x[k][0] = (k + 1);
    }



    for (int i = 0; i < rows; i++)
    {
        System.out.println(" ");

        // Storing City Name

        System.out.print("Enter City Name: ");
        String names = scan.next();
        name[i] = names;

        // Storing Coordinates

        System.out.println("Enter coordinates for " + name[i] + " by (x [enter] y): ");

        for (int j = 1; j < columns; j++)
        {
            x[i][j] = scan.nextInt();
        }

    }

    // --- Printing --- 


    // Prints Out: cityName (x, y)


    System.out.println(" ");

    for (int i = 0; i < rows; i++)
    {
        System.out.print(" ");

        System.out.print(name[i] + " is on (");

        for (int j = 1; j < columns; j++)
        {
            if ( j > 1) 
            {
               System.out.print(", ");
            }

            System.out.print(x[i][j]);
        }

        System.out.print(")");

        System.out.println(" ");
    }


    // Prints Out Distance


    System.out.println(" ");
    System.out.println(" ");

    // Factorial Of Rows

    int z;
    int num = 1;  

    for(z = 1;z <= rows; z++)
    {    
        num = num * z;    
    }     

    int total[] = new int[num];

    // Prints Shortest Distance

    for (int b = 0; b < num; b++)
    {
        System.out.print("The shortest distance from " + name[b]);
        System.out.println(" to " + name[b+1] + " is ");     

        total[b] = Math.sqrt( Math.pow( 2, ( x[b+1][b+1] - x[b][b+1] ) )  +  Math.pow( 2, ( x[b+2][b+2] - x[b][b+2] ) ) );

    }

}

}

1 个答案:

答案 0 :(得分:1)

请改为尝试:

total[b] = (int) (Math.sqrt( Math.pow( 2, ( x[b+1][b+1] - x[b][b+1] ) )  +  Math.pow( 2, ( x[b+2][b+2] - x[b][b+2] ) ) ) );

整数不如double值精确,您将失去精度,如错误中所述。因此,java需要一个显式的强制转换。

这当然不会解决精度的损失。有些情况下这是可以接受的。如果精度损失是可接受的,则必须由开发人员根据具体情况做出决定。如果不能丢失精度,那么除了将变量分配给具有相同或更好精度的其他变量之外别无他法。在这种情况下,数组int[] total必须声明为double[] total

double[] total = new double[num];

for (int b = 0; b < num; b++) {
    total[b] = Math.sqrt( Math.pow( 2, ( x[b+1][b+1] - x[b][b+1] ) )  +  Math.pow( 2, ( x[b+2][b+2] - x[b][b+2] ) ) );
}