猿问

PHP:在 for 循环中出现计算问题

对不起这个愚蠢的问题。我想花费 25 个积分,我的可用积分是 30(10,10,10)。但在我下面的示例代码中,最终数量是减(-)5 值而不是 5。请检查我的代码、实际输出和我的预期结果:


代码:


<?php

$content_credit = 25;

$data = array(10,10,10);

$used_credit = 0;

for($i=0; $i<count($data); $i++){

    if($content_credit > $used_credit){

        $used_credit += $data[$i];

        echo "Point: " . $data[$i];

        echo " Used: " . $used_credit;

        echo " Remaining: " . ($content_credit - $used_credit);

    }

    echo "<br>";

}

实际结果:


Point: 10 Used: 10 Remaining: 15

Point: 10 Used: 20 Remaining: 5

Point: 10 Used: 30 Remaining: -5

预期结果:


Point: 10 Used: 10 Remaining: 15

Point: 10 Used: 20 Remaining: 5

Point: 10 Used: 25 Remaining: 5


慕标5832272
浏览 105回答 3
3回答

慕桂英4014372

$content_credit在第一次迭代中变为 10,然后在第二次迭代中变为 20,因为+=.因此 25 - 10 - 20 = -5

PIPIONE

<?php$credit_to_spend = 25;$available_credit = array(10,10,10);$used_credit = 0;for( $i=0; $i<count($available_credit); $i++ ){&nbsp; &nbsp; if( $credit_to_spend > $used_credit ){&nbsp; &nbsp; &nbsp; &nbsp; $required = ($credit_to_spend - $used_credit);&nbsp; &nbsp; &nbsp; &nbsp; $used_credit += ($required < $available_credit[$i]) ? $required : $available_credit[$i];&nbsp; &nbsp; &nbsp; &nbsp; $remaining = (($required < $available_credit[$i]) ? ($available_credit[$i] - $required): ($credit_to_spend - $used_credit));&nbsp; &nbsp; &nbsp; &nbsp; echo "Point: " . $available_credit[$i]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; . " Used: " . $used_credit&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; . " Remaining: " . $remaining;&nbsp; &nbsp; }&nbsp; &nbsp; echo "<br>";}

蝴蝶不菲

您可能正在寻找类似的东西:<?php$content_credit = 25;$data = array(10,10,10);$total = array_sum($data);$used_credit = 0;for($i=0; $i<count($data); $i++){&nbsp; &nbsp; if($content_credit > $used_credit){&nbsp; &nbsp; &nbsp; &nbsp; $used_credit += $data[$i];&nbsp; &nbsp; &nbsp; &nbsp; echo "Point: " . $data[$i];&nbsp; &nbsp; &nbsp; &nbsp; echo " Used: " . $used_credit;&nbsp; &nbsp; &nbsp; &nbsp; $remaining = $used_credit > $content_credit ? $total - $content_credit :&nbsp; $total - $used_credit;&nbsp; &nbsp; &nbsp; &nbsp; echo " Remaining: " . $remaining;&nbsp; &nbsp; }&nbsp; &nbsp; echo "<br>";}你需要知道你总共有多少信用来计算余额。$used_credit要获得实际使用的信用额度,只需知道和之间哪个值更小就足够了$content_credit。所以你可以min()用来获取价值。echo " Used: " . min($used_credit, $content_credit);类似地,$remaining可以用max()三元运算符结果的值或简单的计算来代替$total - $actual_used。echo " Remaining: " . max($total - $content_credit,&nbsp; $total - $used_credit);
随时随地看视频慕课网APP
我要回答