简体   繁体   English

在for循环中增加一个值

[英]increment a value in for loop

I have the following code for for loop, what I am trying to do is each time the loop runs the next $data needs to be the previous $data * 1.025 我有以下for循环代码,我想做的是每次循环运行时,下一个$data必须是前一个$data * 1.025

$amount = 3150;
$age=22;
for ($x = $age; $x<= 60; $x++){
    $data = $amount*1.025;
    echo "amount_$x = $data<br>";
}

This gives me the following outcome, which is understood because the value of $data never changes 这给了我以下结果,这是可以理解的,因为$data的值永远不会改变

amount_22 = 3228.75
amount_23 = 3228.75
amount_24 = 3228.75
amount_25 = 3228.75

where as the outcome i am looking for should be something like 我正在寻找的结果应该像什么

amount_22 = 3228.75
amount_23 = 3309.47
amount_24 = 3392.20
amount_25 = 3477.01

I will appreciate any help in how to get the next value of $data * 1.025 我将不胜感激如何获取$data * 1.025的下一个值

$amount doesn't change in your loop, so $amount*1.025; $amount不会在循环中更改,因此$amount*1.025; doesn't change either. 也不改变。 Try $data = $data*1.025; 尝试$data = $data*1.025; . Note you'll need to initialize $data = $amount; 注意,您需要初始化$data = $amount; .

You are changing $data based on the same variable $amount . 您正在基于相同的变量$amount更改$data Amount does not change in the loop, so the result is the same. 循环中的金额没有变化,因此结果是相同的。

Try this: 尝试这个:

$amount = 3150;
$age = 22;
for ($x = $age; $x <= 60; $x++){
    $amount = $amount*1.025;
    echo "amount_$x = $amount<br>";
}

Try changing the code to this: 尝试将代码更改为此:

$amount = $amount*1.025;
echo "amount_$x = $amount<br>";

This will increment the amount each time, and changes will be retained since amount is declared outside the loop. 每次都会增加amount ,并且由于amount是在循环外部声明的,因此更改将保留。

Update $amount with each loop. 每次循环更新$amount

Eg 例如

$amount = 3150;
$age=22;
for ($x = $age; $x<= 60; $x++){
    $amount = $amount*1.025;
    echo "amount_$x = $amount<br>";
}

You said the new data has to be the previous data * 1.025, but you're multiplying $amount instead of $data . 您说新数据必须是先前的数据* 1.025,但是您要乘以$amount而不是$data

$data = 3150;
$age=22;
for ($x = $age; $x<= 60; $x++){
    $data = $data*1.025;
    echo "amount_$x = $data<br>";
}

A sweet solution is to assign a variable of the product of $amount and 1.025 for iteration so: 一个不错的解决方案是为变量分配$ amount和1.025乘积的变量,以便:

<?php

$amount = 3150;
$age=22;

for ($x = $age; $x<= 60; $x++){
    $amount = $amount * 1.025;
    echo "amount_$x = $amount<br>";
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM