Repeating structure - 10% "every day"

Asked

Viewed 37 times

0

I can’t make a repeating structure.

Example of what I want to do: I enter the initial value and enter the percentage I want it to increase for 30 days.

Example of starting value: 50. Percentage that increases every day: 10%;

1- R$55,00 (+10%)

2- R$60,50 (+10%)

3- R$66,55 (+10%)

4- ...

      var inicial = parseFloat(prompt("Digite o valor inicial:"));
      var porcentagem = parseFloat(prompt("Digite a porcentagem diária: \nOBS: 10% = 1.10"));

      var calc = parseFloat(inicial * porcentagem).toFixed(2);
      document.write(calc + "<br>");

      for (var i=0; i<=30; i++) {
        var fds = parseFloat(calc * porcentagem).toFixed(2);
        document.write(fds + "<br>")
      }

1 answer

0


Your calc has fixed value throughout the loop time. You have to update the calc every iteration of the loop, as calc is R$5 at the beginning, for when the percentage is 10%, at each loop this percentage must be calculated based on the value of calc that has to be updated.
In the code commented below, we will calculate the value of calc with a function and show the value already at the rate of:

function calculaValorComTaxa(valor, taxa) {
  return (valor * taxa) + valor; // para R$50 e porcentagem de 10%, retorna 55.
}

var inicial = parseFloat(prompt("Digite o valor inicial:"));
var porcentagem = parseFloat(prompt("Digite o valor inicial:")) / 100; // convertemos porcentagem para float dividindo por 100.

var calc = calculaValorComTaxa(inicial, porcentagem); // no primeiro momento, calc sera 55.

document.write(calc + "<br>"); // mostra 55.

for (var i = 0; i <= 4; i++) {

  calc =  calculaValorComTaxa(calc, porcentagem); // agora para cada iteracao, calc vai ser calculado com base no valor anterior, 55, e atualizar o calc para um novo valor. 10% de 55 = 5,5 mais o valor antigo de 55 temos o novo valor de 60,5

  var fds = calc; // valor atualizado de 60,5. 
  
  document.write(fds + "<br>") // exibimos esse valor e refazemos a mesma logica e sempre atualizando o calc ate o fim do loop.

}

Try to take the test and solve your problem.

  • Solved perfectly! Thank you very much!

Browser other questions tagged

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