How to decrease percentually in loop?

Asked

Viewed 50 times

0

I need to make a loop where I have a process where something loses its weight every 1 minute

For example:

100 - 20% = 80
80- 20% = 64
64 - 20% = 51.2

So it will even arrive as a result it is 8.5899

$variavel100 - 20% = $total
$total - 20% = $total2
$total2 - 20% = $total3

So go, how to do it in a loop?

  • Do you want the script to wait 1 minute? Or you can follow the direct loop?

  • need to make a loop with some data ( every 1 day a person who has 100kg loses 10% of their weight so consequently until reaching the weight 47.82969kg) in how long the person lost weight ?

  • But why 47,82969kg?

  • Important to read [Ask] and site scope so I can work out the next ones better. The way it is, it talks in a loop (which is apparently a mere detail) and appears to be a matter of learning to do percentage (which really doesn’t fit the scope). Also, knowing math, will solve the amount of time without any loop.

  • I wrote a post a while ago about a solution to this exact problem. You can apply the compound interest formula to this. This is the link from my post if I help you.

1 answer

1


It can be a simple while checking the current value, something like:

<?php

$peso = 100;
$porcentagem = 20;
$minimo = 8.58994;

while ($peso > $minimo) {
    echo "Atual: $peso\n";
    $peso -= (($peso / 100) * $porcentagem);
}

echo 'Resultado:' , $peso;
  • Here is made the rule of 3: ($peso / 100) * $porcentagem
  • The sign -= indicates to decrease the value itself of the variable that will be set, which would be equivalent:

    $peso = $peso - (($peso / 100) * $porcentagem);
    

Example in IDEONE: https://ideone.com/sNA8mu


Note also that to refer to the 20% you could use a broken number, for example 0.80, then if you want to decrease the value do so:

<?php

$peso = 100;
$porcentagem = .8; //o que deve sobrar e não o que subtrai
$minimo = 8.58994;

while ($peso > $minimo) {
    echo "Atual: $peso\n";
    $peso *= $porcentagem;
}

echo 'Resultado:' , $peso;

Note that .80 is virtually the same thing as 0.80, as well as .8 It’s also pretty much both. And more important is "80%", because the multiplied percentage will result in the value that remains and not the value that you want to decrease.

Example in IDEONE: https://ideone.com/U62596

Browser other questions tagged

You are not signed in. Login or sign up in order to post.