理解java.lang.Math输出的困难
我很难理解为什么输出不同。希望有人能解释这里发生了什么 当我输入理解java.lang.Math输出的困难,java,algorithm,math,floating-point,int,Java,Algorithm,Math,Floating Point,Int,我很难理解为什么输出不同。希望有人能解释这里发生了什么 当我输入2时,下面的代码按预期计算体积和表面积(分别为33.5103和50.2655),但如果我将体积公式从(4.0/3)*Math.PI*Math.pow(r,3)更改到(4/3)*Math.PI*Math.pow(r,3),输出为25.1327 当我将4.0更改为4时,为什么输出不同 import java.lang.Math; // Import the Math class. import java.util.Scanner;
2
时,下面的代码按预期计算体积和表面积(分别为33.5103和50.2655),但如果我将体积公式从(4.0/3)*Math.PI*Math.pow(r,3)更改代码>到(4/3)*Math.PI*Math.pow(r,3)代码>,输出为25.1327
当我将4.0更改为4时,为什么输出不同
import java.lang.Math; // Import the Math class.
import java.util.Scanner; // Import the Scanner class.
import java.text.DecimalFormat; // Import the DecimalFormat class.
class Main {
public static double calcVolume(double r) {
// Return Volume.
return (4.0 / 3) * Math.PI * Math.pow(r, 3);
}
public static double calcSurfaceArea(double r) {
// Return the Surface Area.
return 4 * Math.PI * Math.pow(r, 2);
}
public static void main(String[] args) {
// Prompt user for the radius.
Scanner radius_in = new Scanner(System.in);
System.out.println("Please enter the radius to calculate volume and surface area: ");
Double radius = radius_in.nextDouble();
Double volume = calcVolume(radius);
Double surfaceArea = calcSurfaceArea(radius);
// Set up decimalformat object for outputting to 4 decimal places.
DecimalFormat DF = new DecimalFormat("0.####");
System.out.println("Volume is: " + DF.format(volume));
System.out.println("Surface Area is: " + DF.format(surfaceArea));
}
}
这是因为使用4.0/3
可以获得浮点精度,而4/3
被视为int。这意味着,无论计算为4/3
的值是多少,小数部分都会被截断:
4.0 / 3 => 1.(3)
4 / 3 => (int) (1.(3)) => 1
也许不是复制品,但还是要读。4.0/3
是1.33…
<代码>4/3
是1
。除非至少有一个参数是浮动的,否则除法将是整数。因为4/3返回1,而4.0/3返回1.333修改此问题的标题,以更具体地总结您的特定技术问题。你的问题与其他所有java.lang.Math问题有何不同?即使我将其设置为双精度?我对Java相当陌生,所以我确信我的无知正在显现。方法的返回类型并不重要。方程正在求解,然后根据需要将其转换为double
(返回语句)。因此,因为提供的两个值都是整数,Java正在执行整数除法,并将其转换为double?更精确地说,大括号之间的部分是整数,因此它被解析为整数。