Hypotenuse calculation using formulas with power and square root – Computer Sir Ki Class


Code Learning#JAVA#3784 siteicon   siteicon   siteicon  

Hypotenuse calculation using formulas with power and square root

Creating formulas that contain powers and square root.

Learning Objectives

  • Using formulas with powers and roots.
  • Learning to build entire formula on right hand side only.

Source Code

TC++ #3784

Source Code

class PowRoot
public static void main(String[] args)
double b,h,hy ;
System.out.println("RA triangle given base = "+b+" height = "+h);
System.out.println("Computed hypotenuse = "+hy);

Test it !

Run Output

RA triangle given base = 4.2 height = 3.3
Computed hypotenuse = 5.34

Code Understanding

double b,h,hy ; b=4.2; h=3.3;
Double variables declared and b and h are provided initial values. When you learn to collect input you can collect such values from user.

This is java representation of a popular formula c2=a2+b2 . Since left hand side can not contain an expression so we build the entire formula on the right hand side only. For this the entire formula will be square root of a square + b square. For this reason the java math library metods sqrt() and pow() has been used. These methods are a part of java.lang.math package which is included by default in most programming environments as java.lang.* is usually imported by default.

This is done to truncate a high precision double computed value to 2 decimals. We multiply by 100 convert to integer and then divide by double 100.0 so that result is stored in double.

System.out.println(“RA triangle given base = “+b+” height = “+h);
System.out.println(“Computed hypotenuse = “+hy);
Given and computed values are printed.


Code Notes

  • The hypotenuse calculation will be approximate only due to limitations of precision of such calculations being in double precision. With the use of decimal place truncation or rounding off these values may be further approximated.
  • Instead of truncation one can also use rounding off methods in java such by using DecimalFormat pattern based rounding or Math.round() methods. A good link to see such examples is –

Suggested Filename(s): PowRoot.java


sunmitra| Created: 6-Mar-2018 | Updated: 6-Mar-2018|