ASM2 - The problem is that n1 n2 n3 are integers of int...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Can’t get the correct answer for the average of three input numbers from your program? Let’s look at the body of the program listed below: System.out.println("Programming Assignment # 2"); System.out.println("\n"); System.out.println("Average of Three Integers"); System.out.println("\n"); System.out.println("Please enter three whole numbers on a line:"); int n1, n2, n3; Scanner keyboard = new Scanner(; n1 = keyboard.nextInt(); n2 = keyboard.nextInt(); n3 = keyboard.nextInt(); System.out.println("\n"); System.out.println("The average of the three numbers is"); System.out.println((n1 + n2 + n3) / 3); System.out.println("\n"); The answer from this program will not be as accurate as it should be.
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: The problem is that n1, n2, n3 are integers of int type, and 3 is also an integer. Your answer will be stored as an integer with decimal digits truncated. Try the following methods to correct this problem: a. Typecast the total you summed : System.out.println( (double) (n1 + n2 + n3) / 3); b. System.out.println( (n1 + n2 + n3) / 3 . ); // notice the period after the 3. Why does this work? c. Try to create a variable to hold the sum and a double type variable to hold the average of the three numbers: a. double sum = n1 + n2 + n3; b. double ave = sum / 3; d. Will the following statement produce accurate answer to the 2 nd decimal digit? double ave = (n1 + n2 + n3) / 3;...
View Full Document

This note was uploaded on 01/20/2010 for the course MATH 107 taught by Professor Christinashow during the Spring '08 term at Mesa CC.

Ask a homework question - tutors are online