何时在JAVA代码中使用Float vs Double?

时间:2017-01-06 07:17:55

标签: java double computer-science

有人可以向我展示一个示例示例,我可以在下面的代码中使用Double吗?

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

           System.out.println("Hello, World!");

           int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
           int mySecondNumber = 10;
           int myThirdNumber = 3;
           int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;

           System.out.println(myFirstNumber);//prints variable myFirstNumber
           System.out.println("myFirstNumber ");//
           System.out.println(myTotal);
       }

    }

1 个答案:

答案 0 :(得分:0)

当您需要处理非整数值时,请使用floatdouble(或其装箱对应的FloatDouble)。您发布的代码对此没有明显的需求,因此很难回答您的问题。但是,如果你想计算三个数字的平均值,那就有一种可能性:

public class HelloWorld { public static void main(String[] args) {
    System.out.println("Hello, World!");

   int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
   int mySecondNumber = 10;
   int myThirdNumber = 3;
   int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
   float average = myTotal / 3.0f;

   System.out.println(myFirstNumber);//prints variable myFirstNumber
   System.out.println("myFirstNumber ");//
   System.out.println(myTotal);
   System.out.println(average);
}

关于何时使用floatdouble(问题的标题),如果您可以容忍的舍入误差小于double,则使用float