Sum of numbers in JavaScript [duplicate]

-1

I'm having a hard time doing an exercise that asks for the following:

Using JavaScript, request a number in a prompt box, this number can not be greater than 50, if the number is larger, show an alert box to repeat the number. As a result, show all even numbers from 0 to the number entered, the total even numbers and the sum of these numbers (all numbers entered).

I'm at the beginning of JavaScript, so I do not know much yet. I did it. And the sum is not working, can anyone 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/>")
    
asked by anonymous 16.08.2018 / 13:14

1 answer

1

Switch

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   
}

By

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 since you did not save this value in a variable that conversion to integer was lost. The correct thing is you do this and assign it to a variable, as follows:

soma = parseInt(num)

So the variable soma will get an integer, coming from the num conversion.

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

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

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

soma = soma + parseInt(num)
    
16.08.2018 / 13:23