Java JDK - possible lossy conversion from double to int

后端 未结 2 1300
耶瑟儿~
耶瑟儿~ 2020-12-10 19:26

So I have recently written the following code:

    import java.util.Scanner;

public class TrainTicket
{
      public static void main (String args[])
               


        
2条回答
  •  清歌不尽
    2020-12-10 20:08

    You are trying to assign price* much* 0.7, which is a floating point value (a double), to an integer variable. A double is not an exact integer, so in general an int variable cannot hold a double value.

    For instance, suppose the result of your calculation is 12.6. You can't hold 12.6 in an integer variable, but you could cast away the fraction and just store 12.

    If you are not worried about the fraction you will lose, cast your number to an int like this:

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

    Or you could round it to the nearest integer.

    int total2 = (int) Math.round(price*much*0.7);
    

提交回复
热议问题