Re: sorry .09 instead of .08
- From: James Westby <jw2328@xxxxxxxxxx>
- Date: Sun, 29 Jan 2006 22:46:02 GMT
joshdalrymple2000@xxxxxxxxx wrote:
double totalCost = 3.91, amountPaid = 4.00; int totalChange;
totalChange = (int)((amountPaid - totalCost) * 100); System.out.println(totalChange);
it keeps saying the answer is 8... can any one help?
Try looking at the output of this instead
double totalCost = 3.91, amountPaid = 4.00;
double totalChange;
totalChange = ((amountPaid - totalCost) * 100); System.out.println(totalChange);
You'll see it isn't 9, and the cast to int truncates it to 8, as you were seeing originally.
The problem is that you can't use floating point arithmetic (doubles) to do precise arithmetic. If possible then you should try using fixed point arithmetic. e.g.
int totalCost = 391, amountPaid = 400; int totalChange;
totalChange = amountPaid - totalCost; System.out.println(totalChange);
James .
- Follow-Ups:
- Re: sorry .09 instead of .08
- From: Thomas Hawtin
- Re: sorry .09 instead of .08
- References:
- sorry .09 instead of .08
- From: joshdalrymple2000
- sorry .09 instead of .08
- Prev by Date: sorry .09 instead of .08
- Next by Date: Re: JAR file which needs to call another jar file....
- Previous by thread: sorry .09 instead of .08
- Next by thread: Re: sorry .09 instead of .08
- Index(es):
Relevant Pages
|