views:

197

answers:

3

Hello,

The title says it all, really. I'm trying to get an array of (9) numbers square rooted then printed but I keep coming back with only one result - the number of numbers in the array squared- obviously not what I want. Thanks for any help. Ok, here is my terrible code so far. Trying to pass it to a method as well.

public static void main ( String args[] )
{ 
 double[] nums  = {126, 12.939, 795, 320.16,
             110, 34.7676, 7773, 67, 567, 323};

System.out.println ("Square root is " +square);
square(nums);
} 

public static double square (double [] array) {
double result;
for( double i = 0; i < array.length ; i++ )
  result = Math.sqrt(array[i]);

return result;
 }
}
+4  A: 

You have only a single variable result to store the square roots, so it gets overwritten and in the end it contains only the latest square root. In case you want the square root of each element within the array, you need to store the results in an array as well, e.g.

public static double[] square (double [] array) {
  double[] result = new double[array.length];
  for(int i = 0; i < array.length ; i++ )
    result[i] = Math.sqrt(array[i]);

  return result;
}

Then you can print out the results one by one, e.g. like this:

public static void main ( String args[] )
{ 
  double[] nums  = {126, 12.939, 795, 320.16,
             110, 34.7676, 7773, 67, 567, 323};
  double[] squares = square(nums);

  for(int i = 0; i < nums.length ; i++ )
    System.out.println ("Square root of " + nums[i] + " is " + squares[i]);
}

Update: and the result on my machine, as expected, is:

Square root of 126.0 is 11.224972160321824
Square root of 12.939 is 3.597082150855051
Square root of 795.0 is 28.19574435974337
Square root of 320.16 is 17.893015397076034
Square root of 110.0 is 10.488088481701515
Square root of 34.7676 is 5.896405684821898
Square root of 7773.0 is 88.16461875378354
Square root of 67.0 is 8.18535277187245
Square root of 567.0 is 23.811761799581316
Square root of 323.0 is 17.97220075561143
Péter Török
This doesn't seem to be printing anything!
roger34
@roger34, it does (on my machine, at least :-) - see my update
Péter Török
+1  A: 

If you want to print the square root of all the elements in the array, you have to iterate and print the results in the same method. Something like:

for (int i = 0 ;i < array.length; i++)
{
    System.out.println("The Square Root of " + array[i] + " is" + Math.sqrt(array[i]));
}

The way you are doing is as follows: For each number in your array, find its square root and store it in variable result. Once that you have looped through all the array, return the value of result, which in this case will be the square root of the last number you have processed.

npinti
+1  A: 

In addition to what has been said...it appears you are calling the function after you are printing the answer. Make sure you shore that up too.

The Real Diel