# Simple Addition Program Outputting Wrong Value

• 08-04-2008, 04:40 AM
carlodelmundo
Simple Addition Program Outputting Wrong Value
Quote:

[CODE]import ccj.*;

public class Coins3
{
public static void main(String[] args)
{
/* User Input */
System.out.println("How many pennies do you have?");
int pennies = Console.in.readInt();
System.out.println("How many nickels do you have?");
int nickels = Console.in.readInt();
System.out.println("How many dimes do you have?");
int dimes = Console.in.readInt();
System.out.println("How many quarters do you have?");
int quarters = Console.in.readInt();
/* 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!
• 08-04-2008, 05:36 AM
Eranga
Are you sure that you can compile this code? Console class doesn't have readInt() method as far as I know.
• 08-04-2008, 11:02 AM
Niveditha
Hi,
I feel the following is wrong somewhere
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?
• 08-04-2008, 01:40 PM
Norm
Quote:

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.
• 08-05-2008, 03:37 AM
carlodelmundo
Quote:

Originally Posted by Niveditha
Hi,
I feel the following is wrong somewhere
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