Change Counting Problem - Feedback Requested
There's a common programming challenge where you write a program to take a dollar amount from the user, and then return the simplest way to create that amount with only coins (using the fewest coins possible). I took a crack at this a while back, and I would like to know if there are ways it could be improved or if you would have done it differently.
use strict;
use warnings;
print "Input a dollar amount: ";
my $amount = readline STDIN;
chomp ($amount);
$amount = $amount * 100;
$amount = sprintf($amount);
my $quarter = 25;
my $dime = 10;
my $nickel = 5;
my $penny = 1;
my $qnum = $amount / $quarter;
$qnum = int($qnum);
my $remainder = $amount % $quarter;
my $dnum = $remainder / $dime;
$dnum = int($dnum);
$remainder = $remainder % $dime;
my $nnum = $remainder / $nickel;
$nnum = int($nnum);
$remainder = $remainder % $nickel;
my $pnum = $remainder / $penny;
$pnum = int($pnum);
$remainder = $remainder % $penny;
unless ($qnum == 0) {
print "$qnum quarters\n";
}
unless ($dnum == 0) {
print "$dnum dimes\n";
}
unless ($nnum == 0) {
print "$nnum nickels\n";
}
unless ($pnum == 0) {
print "$pnum pennies\n";
}
There is no commenting because the code is from the site that I put tutorials on. If you want my explanation on why I'm doing something, you can see the tutorial. I won't be rewriting this tutorial, though if I learn any new skills from your comments, I may indeed include them in future tutorials.
Thanks in advance for your time and energy.
Looks like a lot of copy-paste there. How about this?
It's worth noting that this solution also makes using a different currency very easy - just populate the hash accordingly. For example, using British coinage.
I wish there was a way to edit ones comments here. That second link should have been http://gist.github.com/8176950.
Put 1¢ to 24¢ in an array:
One more gem from Toby. Thanks Toby.