I'm writing a program that prints an array containing the sum of the values of two arrays passed as parameters. It all works fine with the exception of the last double value. I want the last value to print as 3.1. Instead it's printing the following:
[5.9, 11.7, 2.4, 3.0999999999999996]
Not sure how to format to print otherwise as I'm not allowed to use a String to solve it. I'm not having that problem with the other values. Here's my code and thanks for the help!
import java.util.*;
class Sum
{
public static void main (String [] args)
{
double [] a1 = {4.5, 2.8, 3.4, 0.8};
double [] a2 = {1.4, 8.9, -1.0, 2.3};
arraySum (a1, a2);
System.out.println (Arrays.toString (arraySum (a1, a2)));
}
public static double [] arraySum (double [] x, double [] y)
{
int length = 0;
double [] sum = new double [x.length];
length = x.length;
for (int i = 0; i <= length - 1; i++)
{
sum[i] = x[i] + y[i];
}
return sum;
}
}