Add a sequence of numbers

1

I'm trying to make an algorithm here with this statement:

  

Given an integer n, n> 0, and a sequence with n integers, determine the sum of the positive integers of the sequence. For example, for the sequence 6-27 0 -5 2 4 your program should write the number 19.

The problem is time to add up. Here's the code I've done:

var numero;
var soma;
for (var i = 0; i < 7 ; ) {
   numero=prompt("Entre com o numero: ");
  parseInt(numero);
   while (numero > 0) { 
    soma = soma + numero;
    numero = 0;
 } 
 i++;
}

document.write("A soma dos positivos é: "+soma);

What happens is that the numbers do not add up and I have no idea how to make them add up.

    
asked by anonymous 21.06.2017 / 21:39

4 answers

2

The problem is that this while will be infinite. You do not actually need it because you are entering the numbers one by one and you can add them soon.

Note also that% of% by itself does nothing, you have to assign this value to a variable, type parseInt(numero); .

Tip:

var numero;
var soma = 0;
for (var i = 0; i < 7; i++) {
  numero = Number(prompt("Entre com o numero: "));
  soma+= numero;
}

document.write("A soma dos positivos é: " + soma);
    
21.06.2017 / 21:49
1

You can use the code below, but I believe you will have trouble explaining it to your instructor.

var soma = (function* () {
  while (true) {
    var numero = prompt("Entre com o numero: ");
    if (numero != null) 
      yield parseInt(numero);
  }
})()

var total = 0;
for (var i = 0; i < 7; i++)
  total += soma.next().value;
  
alert(total);
    
21.06.2017 / 22:10
0

You have two problems:

  • parseInt returns an integer in the specified base

  • The sum variable needs to be initialized

  • var numero;
    var soma = 0;
    for (var i = 0; i < 7 ; ) {
       numero=prompt("Entre com o numero: ");
       numero = parseInt(numero);
       while (numero > 0) { 
        soma = soma + numero;
        numero = 0;
     } 
     i++;
    }
    
    document.write("A soma dos positivos é: "+soma);
        
    21.06.2017 / 21:45
    0

    You did not initialize the value of soma , now that's right! And do not use while , use if , while it will loop infinitely if the number is

    21.06.2017 / 21:51