Sum value of an array?

Asked

Viewed 30 times

1

I’m not being able to show on the screen the sum of each line, the values are adding together with the other lines

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href="">
</head>

<body>
    <script>
        var somatoria = [];
        var soma = 0;

        for(x = 0; x<7; x++){
            for (y = 0; y<5; y++){
                somatoria[y]= Math.floor(Math.random()*100);
                soma += somatoria[y]; 
            }
            document.write(somatoria+" = "+soma+ "<br>");
        }
    </script>
</body>

</html>

1 answer

1


Declare the variable var soma = 0; at the beginning of the first for to reset each line:

var somatoria = [];

for(x = 0; x<7; x++){
   var soma = 0;
   for (y = 0; y<5; y++){
      somatoria[y]= Math.floor(Math.random()*100);
      soma += somatoria[y]; 
   }
   document.write(somatoria+" = "+soma+ "<br>");
}

  • You checked those sums of head to test if everything is ok?

  • Not headfirst, on Windows calculator.

  • Sum only the units, if the unit of the result is equal to the unit of that sum of the units, can rely on!!!!

Browser other questions tagged

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