“Possible loss of precision” in my Java program

后端 未结 5 1266
北荒
北荒 2021-01-03 03:03

I\'m new to Java. I wrote the following code:

import java.io.*;
import java.lang.*;

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


        
相关标签:
5条回答
  • 2021-01-03 03:32

    because you declared the variable as float that mean its take up to four bytes space on random access memory,its not able to store all the data in ram , so you have to declare the variable as a double then it will work.

    0 讨论(0)
  • 2021-01-03 03:35
    d=((u*t)+a*Math.pow(t,x))/2F;
    

    should be

    d=(float)((u*t)+a*Math.pow(t,x))/2F;
    

    or declare d as double as GrahamS suggested.

    0 讨论(0)
  • 2021-01-03 03:37

    Math.pow returns double so you have to have double for 'd'. Or you could also cast 'd' to float.

    0 讨论(0)
  • 2021-01-03 03:39

    Don't use floats in your floating point math calculations unless you have a specific reason for doing so (you don't). The overhead for the preferred type, double, is not much higher and the benefit in accuracy is great.

    0 讨论(0)
  • 2021-01-03 03:50

    It is because Math.pow() returns a double which you then do some calculations with. No matter what calculations you do the precision you will have to deal with is double. Therefore, you get the error message. Solutions:
    1) make the floats double
    2) cast the result to float: d=(float)((u*t)+a*Math.pow(t,x))/2F;

    0 讨论(0)
提交回复
热议问题