当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《JavaJDK-从double到int的可能有损转换》经验,为你挑选了1个好方法。

所以我最近编写了以下代码:

    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运行它时.

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



1> Mathews Math..:

当您转换doubleint,值的精度损失.例如,当您将4.8657(double)转换为int时.int值将为4.Primitive int不存储十进制数字.因此您将丢失0.8657.

在您的情况下,0.7是一个double值(浮点在默认情况下被视为double,除非提到float-0.7f).当你计算时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

推荐阅读
跟我搞对象吧
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有