1. Member
Join Date
Aug 2008
Posts
31
Rep Power
0

Simple Addition Program Outputting Wrong Value

[CODE]import ccj.*;

public class Coins3
{
public static void main(String[] args)
{
/* User Input */
System.out.println("How many pennies do you have?");
System.out.println("How many nickels do you have?");
System.out.println("How many dimes do you have?");
System.out.println("How many quarters do you have?");
/* Calculate totals */
double total = (pennies * 0.01) + (nickels + 0.05) + (dimes * 0.10) + (quarters * 0.25);
System.out.println("Total value = " + total);
}
}[CODE]
When I run the program in command prompt with command "java Coins3" and type "1" for each penny, nickel, dime, and quarter, I receive an output of 1.4100000001 instead of 0.41.

By the way, CCJ is a class package designed for the book I'm reading "Computing Concepts with JAVA Essentials". The Console.in.readInt() function basically asks user input.

The obvious answer is 0.41, but why is it adding 1 to that total?

Thanks!
Last edited by carlodelmundo; 08-04-2008 at 04:45 AM.

2. Are you sure that you can compile this code? Console class doesn't have readInt() method as far as I know.

3. Hi,
I feel the following is wrong somewhere
Java Code:
`double total = (pennies * 0.01) + (nickels + 0.05) + (dimes * 0.10) + (quarters * 0.25);`

"(nickels + 0.05)" should have been "(nickels * 0.05)" isnt it?

4. output of 1.4100000001 instead of 0.41.
That's because computers store numbers in binary not decimal. There are approximations made when converting a real decimal number to binary. If you use int the answer will always be correct.
To use int, store your values as cents vs dollars. For example a nickle would be 5 cents vs .05 dollars. You'll have to format the output to get it to print as dollars.

5. Member
Join Date
Aug 2008
Posts
31
Rep Power
0
Originally Posted by Niveditha
Hi,
I feel the following is wrong somewhere
Java Code:
`double total = (pennies * 0.01) + (nickels + 0.05) + (dimes * 0.10) + (quarters * 0.25);`

"(nickels + 0.05)" should have been "(nickels * 0.05)" isnt it?
Ahh. Thank you! That solved my problem!!

To Norm: Interesting. I'll convert it to cents instead of multiplying it by a decimal value (.01) to avoid this estimation.

Thanks all

Posting Permissions

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