Ciclo for javascript - unexpected result

Asked

Viewed 330 times

-1

I’m having problems solving this issue:

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:

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

When I do tests on the console with caloriesDeTrote(2) I can return 15 but when I test other values comes with wrong result, this is my code:

function caloriasDeTrote(numeroDeVoltas) { 
 var calorias = 0; 
 for (var i = 1; i < numeroDeVoltas; i++) { 
  calorias = 5 + 5 * numeroDeVoltas; 
 } 
return calorias; 
}
  • Explain how the calculation is done and what the expected results are

  • I think it’s the lack of parentheses calorias = 5 + (5 * numeroDeVoltas); , the 5 of the right pq in the first he takes the 5+5 and only then he multiplies. If it were another value, it would make 5+2 and multiply, so it is necessary to put the parentheses. If I understood right, this is it.

  • When the calorie valueDeTrote is 2 the code should return 15 where 5 calories are from the first round (5 * 1) plus 10 calories from the second (5 * 2). And when the value of caloriesDeTrote is 3 should return 30 where 5 calories are from the first round, 10 from the second round and 15 from the third round and so on.

  • What is the need of for then?? just make a multiplication, I do not understand, if you want to sum to each for, or if you want it to multiply at once. @Am44nda

  • @Mariana I already took off the for and left only return 5 + (5 * numeroDeVoltas); and I’ve made many changes and I haven’t got the result I want :(

  • Change calorias = 5 + 5 * numeroDeVoltas; for calorias += 5 * i;

  • @Am44nda looks at an example I made. https://jsfiddle.net/hzarquet/

  • You don’t need the go, like @Mariana said. Nor need the parentheses, the multiplication is always done before the addition due to the precedence of the operators. Try my updated answer.

Show 3 more comments

2 answers

2

There is no reason to loop there, the formula is not iterative. Its function can simply be:

function caloriasDeTrote(numeroDeVoltas) { 
    if (numeroDeVoltas === 1) return 5;
    return 5 + 5 * numeroDeVoltas; 
}
  • I think it’s xy problem. Do it the way she wants with the for and then show why you don’t need for.

-1

Your question is confusing, but I believe that’s it;

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

Browser other questions tagged

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