如何计算10美元的季度,尺寸,镍币和便士的数量?
我知道我需要一段时间,但我不知道会有什么条件。
然后我这样做了:
while(#read from a file)
print $cents
$left = $cents %25 #i did this since quarter is the largest change we have.
之后我不知道如何继续写下有多少季度,硬币,镍币和硬币。
答案 0 :(得分:3)
如果您想要计算出更改,请按分数(不是美元金额)工作,并减去最大硬币的最大数量,然后减去下一个最大硬币的最大数量等。硬币值为1 ,5,10,25,我认为这总是会得出使用最少硬币的答案(尽管不同的硬币不会出现这种情况)。
my $amount_in_cents = 1000; # $10 * 100¢/$
my @coins = (25, 10, 5, 1);
my @change;
for my $coin (@coins) {
push @change, int($amount_in_cents / $coin);
$amount_in_cents -= $change[-1] * $coin;
}
say join ', ', map "$change[$_]x$coins[$_]¢", grep $change[$_], 0..$#coins;
答案 1 :(得分:0)
您可以从查看如何使用一枚硬币开始:
my $break_apart = 1000; # ten dollars, in pennies
my $break_into = 25; # a quarter
my $remainder = $break_apart % $break_into;
my $count = ($break_apart - $remainder) / $break_into;
然后扩展它以使用多个硬币:
my @coins = (1, 5, 10, 25);
my $break_apart = 1000; # ten dollars, in pennies
for my $break_into (@coins)
{
my $remainder = $break_apart % $break_into;
my $count = ($break_apart - $remainder) / $break_into;
}