Function to calculate calories

Asked

Viewed 1,779 times

2

Create a function called caloriasDeTrote(), which receives per parameter the number of turns represented by a numerical value and returns the amount of calories that will be consumed.

For example: calling the function caloriasDeTrote(2)

Should return 15 where 5 calories are from the first round (5 * 1) plus 10 calories from the second (5 * 2).

So I tried to create the following function:

  function caloriasDeTrote(numeroDeVoltas) { 
 var calorias = 0; 
 for (var i = 0; i < numeroDeVoltas; i++) {  
  calorias = 5 * numeroDeVoltas

 } 
return calorias; 
}

caloriasDeTrote(2)

Only the result does not come out as expected, because in this example, when calling the function caloriasDeTrote(2), should return number 15 and not 10.

For caloriasDeTrote(1) is equal to 5 (5 * 1) and caloriasDeTrote(2) is equal to 10 (5* 2) so the function should add up the values resulting in 15. This would be the logic on.

  • do calorias += 5 * i; or turn the function into a PG: function caloriasDeTrote(voltas) { return (voltas == 1)? 5 : 5 + 5 * voltas;}

  • @Augustovasques thanks for the return but it didn’t work, I used the following function: Function caloriesDeTrote(turns) { Return (turns == 1)? 5 : 5 + 5 * turns} but when I call the function with the value 3 caloriesDeTrote(3) it returns 20 and should return 30, because it would be (51) = 5 + (52) = 10 + (5*3) = 15 , thus 5+10+15 = 30

2 answers

4


One of the mistakes is that it’s not accumulating calories every time. Another is that in this case it is one of the rare ties that should start from 1 and not from 0 and end when you arrive at the desired lap (you can even do it the traditional way, but you have to do it, it’s worse). And the last mistake is that it is always multiplying by the number of turn and not by the current turn before accumulating.

function caloriasDeTrote(numeroDeVoltas) { 
    var calorias = 0; 
    for (var i = 1; i <= numeroDeVoltas; i++) calorias += 5 * i;
    return calorias; 
}
console.log(caloriasDeTrote(2));

I put in the Github for future reference.

I think you can optimize more, but so solve the problem without inventing too much.

  • thanks for the help, it worked and I was able to understand where the error was. Thank you

0

function caloriasDeTrote(numeroDeVoltas) {
  var quantidadeDeCalorias = 0;

  for (var i = 0; i <= numeroDeVoltas; i++){
    quantidadeDeCalorias += 5 * i;
  }

  return quantidadeDeCalorias;
}

Browser other questions tagged

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