[RESOLVED] Formatting output of a Double
This program works, somewhat, but there is something strange going on here. For example, when you run it with the values below, you get a Total of 12.989898988, or something to that effect. The correct answer, as you can see, is 12.99, when all of the elements of the array are added together. Can anyone tell me why this is happening? I am new to Java, and trying to learn it myself.
3.14
1.49
0.99
3.26
4.11
The Total returned should be 12.99
Here is the code. Thanks.
Code:
public class PriceArray
{
// Create main Method
public static void main(String[] args)
{
// Create array to hold 5 prices, declare variables
double[] priceList = new double[5];
Scanner sc = new Scanner(System.in);
// Get prices from the user and put them into the priceList array
System.out.println("Please enter a price: ");
int price;
for (price=0; price < priceList.length; ++price)
{
System.out.print("Price "+(price+1)+": ");
priceList[price] = sc.nextDouble();
if (priceList[price]<0)
break;
}
System.out.println("Thank you!");
System.out.println("Total: " + sumArray(priceList));
System.out.println("Average: ");
System.out.println("High Prices: ");
}
// Create sumArray Method
public static double sumArray(double[] priceList)
{
// Declare variables
double sum = 0;
//Calculate the um of the elements in the PriceList Array
for (int i = 0; i < priceList.length; i++)
{
sum += priceList[i];
}
return sum;
}
Re: Formatting output of a Double
The problem is in the System.out.println. For example, try the following
Code:
System.out.printf("%f", 3.14 + 1.49 + 0.99 + 3.26 + 4.11);
It will print the correct value