【发布时间】:2019-08-06 04:42:36
【问题描述】:
我很难理解为什么输出不同。希望有人可以解释这里发生了什么。
当我输入 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));
}
}
【问题讨论】:
-
也许不是重复的,但还是请阅读stackoverflow.com/questions/4685450/…。
-
4.0 / 3是1.33...;4 / 3是1。除非至少有一个参数是浮动的,否则除法将是整数。 -
因为 4/3 返回 1,而 4.0/3 返回 1.333
-
修改此问题的标题以更具体地总结您的特定技术问题。您的问题与所有其他 java.lang.Math 问题有何不同?
标签: java algorithm math floating-point int