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

所以我最近写了下面的代码:

    import java.util.Scanner;

public class TrainTicket

{

public static void main (String args[])

{

Scanner money = new Scanner(System.in);

System.out.print("Please type in the type of ticket you would like to buy.\nA. Child B. Adult C. Elder.");

String type = money.next();

System.out.print("Now please type in the amount of tickets you would like to buy.");

int much = money.nextInt();

int price = 0;

switch (type)

{

case "A":

price = 10;

break;

case "B":

price = 60;

break;

case "C":

price = 35;

break;

default:

price = 0;

System.out.print("Not a option ;-;");

}

if (price!=0)

{

int total2 = price* much* 0.7;

System.out.print("Do you have a coupon code? Enter Y or N");

String YN = money.next();

if (YN.equals("Y"))

{

System.out.print("Please enter your coupon code.");

int coupon = money.nextInt();

if(coupon==21)

{

System.out.println("Your total price is " + "$" + total2 + ".");

}

else

{

System.out.println("Invalid coupon code, your total price is " + "$" + price* much + ".");

}

}

else

{

System.out.println("Your total price is " + "$" + price* much + "." );

}

}

money.close();

}

}

但是,它一直显示:

TrainTicket.java:31: error: incompatible types: possible lossy conversion from double to int

int total2 = price* much* 0.7;

当我尝试使用cmd运行它时。

有人可以帮助并解释我所犯的错误吗?任何帮助表示赞赏:)。谢谢!

回答:

当您转换doubleint,值的精度损失。例如,当您将4.8657(double)转换为int时,int值将为4.Primitive

int不存储十进制数字,因此您将丢失0.8657。

在您的情况下,0.7是一个双精度值(除非提到float-0.7f,否则浮点默认情况下被视为double)。计算时price*much*0.7,答案是一个双精度值,因此编译器不允许您将其存储在整数类型中,因为这可能会导致精度损失。也就是说possible

lossy conversion,您可能会失去精度。

那你能做什么呢?您需要告诉编译器您确实想要这样做。您需要告诉编译器您知道自己在做什么。因此,使用以下代码将double显式转换为int:

int total2= (int) price*much*0.7;

/*(int) tells compiler that you are aware of what you are doing.*/

//also called as type casting

在您的情况下,由于您正在计算成本,因此建议您将变量声明total2为double或float类型。

double total2=price*much*0.7;

float total2=price*much*0.7;

//will work

以上是 Java JDK-从double到int的可能有损转换 的全部内容, 来源链接: utcz.com/qa/424518.html

回到顶部