Averaging Errors

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kid Programmer
    New Member
    • Mar 2008
    • 176

    Averaging Errors

    Hello guys. Whenever I am learning a new programming language I like to learn the basics (variables, loops, conditionals etc) by writing a program that will calculate averages. I wrote a simple number averaging program. But when I run it
    in Eclipse or the command line and I enter:
    1
    3
    5.5

    It says the average is 3.1666666666666 665 when it should be 3.1666666666666 667. I checked and am positive it is dividing the sum by 3. What do I do? Here is my source:

    Code:
    /* Title: Number Averaging Program
     * Author: Kid Programmer
     * Language: Java
     * Integrated Development Enviroment: Eclipse
     * Description: This program will prompt a user to enter numbers.  When the user enters a double or string the program will calculate 
     * the average and print it out.  The program will then end.
     */
    import java.util.Scanner;		//import a scanner
    
    public class NumberAverager {	//create a class
    	
    	public static void main(String[] args) throws InterruptedException {		//start the main function
    		double divideby = 0, number = 0, sum = 0, average = 0;			//declare variables
    		Scanner scan = new Scanner(System.in);			//create a scanner named "scan"
    		
    		//explain the program
    		System.out.println("  Loading finished.");
    		System.out.println("This program will average numbers.");
    		System.out.println("If you type with a number the program will not work.  If you type text before typing a number the program will not work.");
    		System.out.println("To stop averaging numbers enter anything that is not a whole number.");
    		System.out.println("Press enter after each number has been entered.");
    		System.out.println("If the number is big, it will cancel the program.");
    		System.out.println("Please enter the numbers: ");
    		
    		//create a loop to execute as long as the user enters numbers
    		while ( scan.hasNextDouble() ) {
    			number = scan.nextDouble();		//prompt the user for numbers
    			sum = sum + number;				//add up the numbers
    			divideby ++;					//increase the amount to divide the numbers by
    			
    			//if the user enters text
    			if ( scan.hasNextDouble() == false) {		
    				average = sum / divideby;			//calculate the average
    				//print the average
    				System.out.print("The total average of the numbers is ");
    				System.out.print(average);
    				System.out.println(".");
    			}
    		}
    	}
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Read this: What every computer scientist should know about floating-point arithmetic.

    kind regards,

    Jos

    Comment

    Working...