![](/img/trans.png)
[英]Keep getting "possible lossy conversion from double to int" error in Java
[英]Java JDK - possible lossy conversion from double to 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运行它时。
有人可以帮助并解释我所犯的错误吗? 任何帮助表示赞赏:)。 谢谢!
当您将double
转换为int
,该值的精度会丢失。 例如,当您将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
您试图将price* much* 0.7
(这是一个浮点值( double
))分配给整数变量。 double
不是精确的整数,因此通常int
变量不能容纳double
值。
例如,假设您的计算结果为12.6
。 您不能将12.6
保留在整数变量中,但可以舍弃分数并仅存储12
。
如果您不担心会损失的分数,则将数字转换为如下的int
:
int total2 = (int) (price* much* 0.7);
或者,您也可以将其舍入到最接近的整数。
int total2 = (int) Math.round(price*much*0.7);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.