javacalculator

How to find the surface area of a pyramid in Java programming (CodeHS)?


I have an assignment on CodeHS to program a calculator for the surface area of a pyramid and it prints out the wrong surface area off by a few decimals. I don't see how this is incorrect (code below).

I've already tried plugging in the formula from Google for surface area and it did not work and printed the wrong number.

 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));

Example: for a pyramid with length 1, width 3, and height 5 it is supposed to print 23.29 but it prints 23.69 and I don't know why?


Solution

  • Another alternative solution: this is the equation for surface area of a right rectangular pyramid:

    enter image description here

    This can be simply written as:

        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);
        }