简体   繁体   中英

Using the Pythagorean theorem with Java

I'm trying to create this program that essentially solves the 3rd value of a right triangle.

So the hypotenuse will always be 1, and one of the values (lets call it 'x') will be greater than or equal to -1 but less than or equal to 1.

First, I created a loop to include all values of x:

   int i = 10;

   while (i >= -10)
   {
       double x = i / 10.0;
       i--;

       System.out.println(x);

    } 

Now, I get a nice list that gives me the values for x. I now need to use that to calculate the values of the third length of the triangle. I can do this using the Pythagoras Theorem. Here it is:

double firsty = Math.pow(1, 2) - Math.pow(x, 2);
double y = Math.sqrt(firsty);

When I put this in the while loop and then write a print statement for y, the results are formatted in a way that lists the first value of x, then the first value of y, then the second value of x, and then the second value of y. How can I change the formatting so that it just has two separate rows, one column that has the values of x and another column that has the values of y?

What I tried doing originally is using an array to hold the values of x in, but I can't calculate the values of the 3rd length by using an array without getting the compiler to yell 'ERROR' at me!

Using the printf function is what needs to be done (pretty sure), but I get a error message when I use printf for the output of x and y.

Based on your question, it appears you've forgotten to take the square root of y . The Pythagorean formula is c 2 = a 2 + b 2 . So, I think you're looking for

double y = Math.sqrt(Math.pow(1, 2) - Math.pow(x, 2));

and to format it you might use a DecimalFormat or String.format like

String str = String.format("%.2f", y); // <-- 2 decimal places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM