【问题标题】:Difficulties understanding java.lang.Math output [closed]理解 java.lang.Math 输出的困难[关闭]
【发布时间】: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 / 31.33...4 / 31。除非至少有一个参数是浮动的,否则除法将是整数。
  • 因为 4/3 返回 1,而 4.0/3 返回 1.333
  • 修改此问题的标题以更具体地总结您的特定技术问题。您的问题与所有其他 java.lang.Math 问题有何不同?

标签: java algorithm math floating-point int


【解决方案1】:

这是因为 4.0 / 3 获得浮点精度,而 4 / 3 被视为 int。这意味着,无论被评估为4 / 3,小数部分都会被截断:

4.0 / 3 => 1.(3)
4 / 3 => (int) (1.(3)) => 1

【讨论】:

  • 即使我将其设置为 Double?我对 Java 还很陌生,所以我敢肯定。
  • 方法的返回类型无关紧要。正在求解等式,然后根据需要将其转换为double(在返回语句中)。
  • 啊。那么因为提供的两个值都是整数,Java 正在执行整数除法并将其转换为双精度数?
  • 更准确地说,大括号之间的部分是整数,所以它被解析为整数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多