【问题标题】:How to find the surface area of a pyramid in Java programming (CodeHS)?如何在 Java 编程(CodeHS)中找到金字塔的表面积?
【发布时间】:2019-02-17 02:52:43
【问题描述】:

我在 CodeHS 上有一个任务,要编写一个计算金字塔表面积的计算器,它会打印出错误的表面积,减去小数点后几位。我看不出这是不正确的(下面的代码)。

我已经尝试插入来自 Google 的表面积公式,但它不起作用并打印了错误的数字。

 public double surfaceArea() {
  double hw = (double)width/2;
  double hl = (double)length/2;
  double slantHeight1 = ((double)Math.sqrt( (double)height*height + 
   (double)hw*hw ));
  double slantHeight2 = ((double)Math.sqrt( (double)height*height + (double)hl*hl ));

  return (double)(((double)0.5 * 2 * slantHeight1 * width)
  + ((double)0.5 * 2 * slantHeight2 * length) 
  + (length * width));

示例:对于长度为 1、宽度为 3、高度为 5 的金字塔,它应该打印 23.29,但它打印出 23.69,我不知道为什么?

【问题讨论】:

  • 您的公式在数学符号中是什么样的?当您使用该公式在计算器上进行计算时,它是否产生了正确的结果?如果是这种情况,您可能会遇到 StackOverflow 主题的编程问题 - 如果不是,您仍然停留在不是 StackOverflow 主题的数学领域。
  • 另请注意-您的代码不完整-您需要发布minimal reproducible example,我们可以编译和运行。目前尚不清楚widthheight 来自何处以及如何声明它们。
  • 但是您可能只是遇到浮点不准确的情况 - 浮点计算并不精确,每次计算都会从精确结果中引入一定量的错误。
  • @ErwinBolwidt 它在计算器上工作。宽度、高度、长度是 Pyramid 类的一部分,然后有一个单独的测试器类。它们是私有实例变量。

标签: java calculator


【解决方案1】:

另一种替代解决方案:这是直角棱锥的表面积方程:

这可以简单地写成:

    public static void main(String[] args) {

        double length = 1;
        double width = 3;
        double height = 5;
        double resultPyramidArea = (length * width) + (length * Math.sqrt(Math.pow(width / 2, 2) +
                Math.pow(height, 2))) + (width * Math.sqrt(Math.pow(length / 2, 2) + Math.pow(height, 2)));

        System.out.println(resultPyramidArea);
    }

【讨论】:

    【解决方案2】:

    改变这个:

      return (double)(((double)0.5 * 2 * slantHeight1 * width)
      + ((double)0.5 * 2 * slantHeight2 * length) 
      + (length * width));
    

    到这里:

      return (double)(((double)0.5 * 2 * slantHeight1 * length)
      + ((double)0.5 * 2 * slantHeight2 * width) 
      + (length * width));
    

    你把公式弄错了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-25
      • 2020-02-11
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多