(Untitled)

Jan 16, 2009 10:21

I've received some very good comments to my blog, concerning the style of my comments in source code. It's true that in professional projects, very obvious comments are counterproductive, especially when changes are made to the code they are explaining. However, for the time being, I'm trying to remember Java itself, not the decisions particular to ( Read more... )

hacking, python

Leave a comment

Overkill anonymous February 7 2009, 07:53:59 UTC
Keeping track of the change is overkill. You don't need to. Just picture it with real pennies. It's extra unnecessary computation. As for partial penny issue, multiply by 100.0, not 100.

Converting to integers is the right way to do this problem since if you try to divide the values as a double, you would have to round all the values and sometimes get a missing penny if you don't which is waste of space and processing. Try it with $100.07 and you'll see you'd get 1 penny at the end instead of two.

import java.util.Scanner;
public class Money
{
public static void main (String[] args)
{
System.out.print("Enter amount: ");
Scanner in = new Scanner(System.in);

double dblmoney = in.nextDouble();
int money = (int)(dblmoney * 100.0);

int tens = money / 1000;
int fives = (money % 1000) / 500;
int ones = (money % 500) / 100;
int quarters = (money % 100) / 25;
int dimes = (money % 25) / 10;
int nickels = (money % 10) / 5;
int pennies = (money % 5);

System.out.println(tens + " ten dollar bills");
System.out.println(fives + " five dollar bills");
System.out.println(ones + " one dollar bills");
System.out.println(quarters + " quarters");
System.out.println(dimes + " dimes");
System.out.println(nickels + " nickels");
System.out.println(pennies + " pennies");
}
}

Reply


Leave a comment

Up