有人可以向我展示一个示例示例,我可以在下面的代码中使用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);
}
}
答案 0 :(得分:0)
当您需要处理非整数值时,请使用float
或double
(或其装箱对应的Float
和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;
float average = myTotal / 3.0f;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
System.out.println(average);
}
关于何时使用float
与double
(问题的标题),如果您可以容忍的舍入误差小于double
,则使用float