0

I created a method to run through an array add the numbers together in the array and then find the square root of the total. But when i checked the square root of the total on a calculator I got an entirely different answer and I was concerned.

The answer I got on the calculator was 3.16227766017. When I ran the code the answer I got was 2.4850206733870595

I am a beginner to coding but I wanted to make sure I did not make an error somewhere in my code. Code is as follows:

public static void main(String[] args) { double array1[] = {1,2,3,4}; double total = 0; for(double x : array1){ total += x; total = Math.sqrt(total); } System.out.println(total); } 

run:

2.4850206733870595 BUILD SUCCESSFUL (total time: 2 seconds) 
1
  • The answers below are, of course, correct. As a more general lesson -- we're often tempted to suspect language-level bugs when we can't figure out what we're doing wrong. This temptation is nearly always misguided, however. Commented Mar 8, 2015 at 20:12

2 Answers 2

3

You want to compute the square root after the for loop finishes:

for (double x : array1) { total += x; } total = Math.sqrt(total); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Manouti. Fixed problem :-)
+1, though it would be better not to reuse the total variable at all. Changing the meaning of a variable (first it means the running total, then it means the square-root of the final total) is always a recipe for trouble.
2

your error is that you are changing total and setting it equal to the square root every time inside the for loop

 for(double x : array1){ total += x; total = Math.sqrt(total); } 

which is obviously wrong. just do it once when the loop is done:

class root { public static void main(String[] args) { double array1[] = {1,2,3,4}; double total = 0; for(double x : array1){ total += x; } total = Math.sqrt(total); System.out.println(total); } } 

and you will get the correct result when you print

3.1622776601683795 

2 Comments

Thank you adrCoder for your help. Fixed.
Glad it worked. Please accept my answer by clicking the tick box on the left of my answer, below the arrow

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.