Results 1 to 2 of 2

Thread: [RESOLVED] Formatting output of a Double

  1. #1

    Thread Starter
    Member
    Join Date
    Dec 2009
    Posts
    44

    Resolved [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;
    	}
    Last edited by CarlMartin10; Apr 11th, 2010 at 03:46 PM.

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Formatting output of a Double

    The problem is in the System.out.println. For example, try the following
    Code:
    System.out.printf("&#37;f", 3.14 + 1.49 + 0.99 + 3.26 + 4.11);
    It will print the correct value
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width