Java JDK - possible lossy conversion from double to int

后端 未结 2 1289
耶瑟儿~
耶瑟儿~ 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);
    
    0 讨论(0)
  • 2020-12-10 20:29

    When you convert double to int,the precision of the value is lost. For example, When you convert 4.8657 (double) to int.The int value will be 4.Primitive int does not store decimal numbers.So you will lose 0.8657.

    In your case,0.7 is a double value(floating point treated as double by default unless mentioned as float-0.7f). When you calculate price*much*0.7 ,the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision.So that's what is possible lossy conversion,you may lose precision.

    So what could you do about it? You need to tell the compiler that you really want to do it.You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:

    int total2= (int) price*much*0.7;
     /*(int) tells compiler that you are aware      of what you are doing.*/
     //also called as type casting
    

    In your case,since you are calculating the cost,I'll suggest you to declare variable total2 as the type double or float.

    double total2=price*much*0.7;
     float total2=price*much*0.7;
     //will work
    
    0 讨论(0)
提交回复
热议问题