Sum of numbers in Javascript

Asked

Viewed 2,492 times

-1

I’m having trouble doing an exercise that asks for the following:

Using Javascript, ask for a number in a prompt box, this number cannot be higher than 50, if the number is higher, show an alert box to repeat the number. As a result, show all even numbers from 0 to the number given, the total even numbers and the sum of these numbers (all numbers typed).

I’m at the beginning of Javascript, so I don’t know much yet. I managed to do this. And the sum is not working, someone can give me a light on the rest?

document.write("EXERCÍCIO 13" + "<br/>" + "<br/>");
var num, par, contPar = 0, soma = 0;
num = prompt("Digite um número: ");
parseInt(num)
parseInt(soma)
soma = num
while (num != 0 || num > 50) {
    num = prompt("Digite um número abaixo de 50 ou 0 para finalizar:");
    soma = soma + num

if (num % 2 == 0)
    contPar = contPar + 1   
}
document.write("Quantidade de números Pares digitados: " + contPar + "<br/>" + "<br/>")
document.write("Soma dos números digitados: " + soma + "<br/>" + "<br/>")

1 answer

1


Change

parseInt(num)
parseInt(soma)
soma = num
while (num != 0 || num > 50) {
    num = prompt("Digite um número abaixo de 50 ou 0 para finalizar:");
    soma = soma + num

if (num % 2 == 0)
    contPar = contPar + 1   
}

For

soma = parseInt(num)
while (num != 0 || num > 50) {
    console.log(soma)
    num = prompt("Digite um número abaixo de 50 ou 0 para finalizar:");
    soma = soma + parseInt(num)

    if (num % 2 == 0)
        contPar = contPar + 1
}

When you do

parseInt(num)
parseInt(soma)

You are converting the value of the variable to integer and returning, but as you did not save this value in a variable this conversion to integer was lost. The correct thing is for you to do this and assign it to a variable, as follows:

soma = parseInt(num)

Thus the variable soma you will receive an integer number from the variable conversion num.

Even if you used parseInt in the variable num, when she receives a value from prompt will again receive a type value string

num = prompt("Digite um número abaixo de 50 ou 0 para finalizar:");

Then again when adding up you will have to use parseInt in the variable when summing

soma = soma + parseInt(num)
  • Now it was clear, thank you very much!! And it worked, thanks very much! D

Browser other questions tagged

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