$money = 100000; // the original money I have
$a = 0; // $a defines how many times I can spend the money
// When the money I have is more than 50,000, I spend 5% of them as the pass-door fee.
while ($money > 50000) {
$money= $money * 0.95; // The money left after each spending
$a++; // How many times I can spend the money.
}
echo $a.'<br>'; //$a=14 So far I have passed the door 14 times.
echo $money.'<br>'; //$money=48767.497911553 So far I have 48767.497911553 money left.
我的问题是为什么以下代码不起作用?
// When the money I have is equal to or less than 50,000, I spend 5,000 as the pass-door fee.
while($money<=50000) {
$money = $money - 5000; // The money left after each spending
$a++; // How many times I can spend the money.
}
echo $a.'<br>';
echo $money. '<br>';
答案 0 :(得分:2)
在你的第二个循环中,只要你少于50,000,你就会通过,因为你只减少了你的金额,你将永远留在那里,我想你想要在达到0美元或更低时停止它,所以你可以这样做:
while($money >= 0 && $money<=50000)
在这种情况下,只要您达到0或更低,循环就会停止减少您的资金。如果你想循环,直到你不能再支付费用,只需:
while($money >= 5000 && $money<=50000)
答案 1 :(得分:2)
首先我检查我还有钱:
$money = 100000; //the original money I have
$a= 0 ; // $a defines how many times I can spend the money
$b = 0; //defines how many turns I have done;
while($money>0){
if($money>50000){ //First option - i loose 5% of my money
$money = $money * 0.95;
$b = $b+1;
}else{ //I already know that I have money
if($money>5000){ //I can do another turn
$money = $money - 5000;
$b = $b + 1;
}else{ //I have less then the money I need to do another turn
echo "You made $b turns and now you have only $money left";
$money = 0; //I reset the money so I get out of the while loop
exit(); //i go out of the loop since I have nothing more to spend
}
}
}
使用这些数字,此代码的结果将是:
你做了23回合,现在只有3767.497911553
如果您还想模拟转弯时剩余的次数,我也无法得到。这将导致程序的不同设置。
答案 2 :(得分:1)
while($money<=50000)
你的钱永远不会超过你的第二个循环中的50000
,因为你只需减少它$money=$money-5000;
就可以进入一个无限循环。
答案 3 :(得分:1)
问题是你的第二个循环条件:
while($money<=50000)
这将永远是真实的,因为你正在减少你的钱。
所以它应该是while ($money >= 5000)
因为你必须至少有5000来支付费用