Results 1 to 5 of 5
- 08-04-2008, 04:40 AM #1
Member
- Join Date
- Aug 2008
- Posts
- 31
- Rep Power
- 0
Simple Addition Program Outputting Wrong Value
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.[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]
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.
- 08-04-2008, 05:36 AM #2
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
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 #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?To finish sooner, take your own time....
Nivedithaaaa
- 08-04-2008, 01:40 PM #4
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.output of 1.4100000001 instead of 0.41.
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 #5
Member
- Join Date
- Aug 2008
- Posts
- 31
- Rep Power
- 0
Similar Threads
-
what is wrong with this program ?
By Poor Bee in forum New To JavaReplies: 1Last Post: 05-07-2008, 07:23 PM -
Addition program that displays the sum of two numbers
By Java Tip in forum Java TipReplies: 0Last Post: 03-28-2008, 08:46 PM -
Peculiarty in code of simple program...
By Kreuz14 in forum New To JavaReplies: 4Last Post: 01-23-2008, 03:27 AM -
help with simple program in java
By katie in forum New To JavaReplies: 2Last Post: 08-06-2007, 08:03 PM -
help with simple java program
By leonard in forum New To JavaReplies: 3Last Post: 07-30-2007, 09:40 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks