我用PHP制作了ATM机,但是我使用了4个for循环。我只想使用一个循环和一个数组。这是我的代码:
private function Atm() {
$nAmount = $_POST['txtATM'];
$nFifty = 0;
for ($V=0; $V < $nAmount; $V+=50) {
$nFifty++;
}
if ($V > $nAmount) {
$V-=50;
$nFifty-=1;
}
$nTwenty = 0;
for ($T=$V; $T < $nAmount; $T+=20) {
$nTwenty++;
}
if ($T > $nAmount) {
$T-=20;
$nTwenty-=1;
}
$nTen = 0;
for ($t=$T; $t < $nAmount; $t+=10) {
$nTen++;
}
if ($t > $nAmount) {
$t -= 10;
$nTen-=1;
}
$nFive = 0;
for ($v=$t; $v < $nAmount; $v+=5) {
$nFive++;
}
if ($v > $nAmount) {
$v-=5;
$nFive-=1;
}
echo "You will get: ";
echo "$nFifty times fifty, $nTwenty times twenty, $nTen times ten and $nFive times five. ";
}
有人可以帮助我找到一个仅用一个循环和一个数组重写此代码的解决方案吗?
答案 0 :(得分:1)
您可以使用1个循环来执行此操作(在这种情况下,我更喜欢):
$arr = array(50, 20, 10, 5);
$name = array("fifty", "twenty", "ten", "five");
$v = 105;
while ($v && count($arr)) {
$currentBill = array_shift($arr);
$change[] = intval($v / $currentBill);
$v = $v % $currentBill;
}
for ($i = 0; $i < count($change); $i++)
echo $change[$i] . " of ". $name[$i] .", ";
我建议在开头添加错误检查,以将其除以5等等,以此类推...
答案 1 :(得分:0)
我将计算模数以检查有效面额,然后在循环中重复进行整数除法,以循环方式设置字符串为 n次面额的字符串,然后以逗号分隔,最后一个除外由'and'
分隔。
取模运算的结果是整数除法的其余部分。如果最小面额上有剩余,则无法付款。
整数除法为您提供特定面额的计数。我们从最伟大的开始。残余物将使用下一个较小的面额进行处理。
function Atm(int $amount)
{
$denominations = [50 => 'fifty', 20 => 'twenty', 10 => 'ten' , 5 => 'five'];
if($amount <= 0 || $amount % array_key_last($denominations))
return 'Amount cannot be paid. $5 is the smallest denomination.' . PHP_EOL;
$arr = [];
foreach($denominations as $denomination => $name)
{
$amount -= $denomination * $count = (int) ($amount / $denomination);
if($count)
$arr[] = "$count times $name";
}
return 'You will get: '
. (1 === count($arr) ? $arr[0] : implode(', ', array_splice($arr, 0, -1)) . ' and ' . $arr[0])
. '.' . PHP_EOL;
}
var_dump(Atm(5));
var_dump(Atm(105));
var_dump(Atm(115));
var_dump(Atm(116));
输出:
string(28) "You will get: 1 times five.
"
string(46) "You will get: 2 times fifty and 1 times five.
"
string(59) "You will get: 2 times fifty, 1 times ten and 1 times five.
"
string(52) "Amount cannot be paid. $5 is the smallest denomination.
"
TODO:您应该编写一个例程来输出“一次”,“两次”,“ n次”或查找其他表达式,例如“ 1张钞票”,“ 2张钞票”。