cs106a – Assignment #2 – Task #4

In high-school geometry, you learned the Pythagorean theorem for the relationship of the lengths of the three sides of a right triangle:
a2 + b2 = c2
which can alternatively be written as:
c = √(a2 + b2)
Most of this expression contains simple operators covered in Chapter 3. The one piece that’s missing is taking square roots, which you can do by calling the standard function Math.sqrt. For example, the statement

double y = Math.sqrt(x);

sets y to the square root of x.
Write a ConsoleProgram that accepts values for a and b as ints and then calculates the solution of c as a double. Your program should be able to duplicate the following sample run:

cs106a – assignment #2 – task #4

Start by printing the initial instructions. Read both integers. Calculate the hypotenuse and print it:

	public void run() {
		println("Enter values to compute Pythagorean theorem.");
		int a = readInt("a: ");
		int b = readInt("b: ");
		double c = Math.sqrt(a * a + b * b);
		println("c: " + c);

The code for this assignment is available on github.


Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *