0
Necesito ayuda con este codigo
function main() { //tomando el número de vuelo y su estado var levels = parseInt(readLine(),10); var points = new Array(); var count = 0; while(count<levels){ var elem = parseInt(readLine(),10); points[count] = elem; count++; } var sum = 0; //calcula la suma de puntos //la salida console.log(sum); }
1 Antwort
+ 2
Seems like you want to calculate the sum of all values stored in points array.
Here's the snippet that will solve your problem:
// calculating sum of elements in array points
var sum = 0;
for(var count = 0; count < levels; count++) {
sum = sum + points[count];
}
Since you know how many elements you need to read, a FOR loop is the best choice.
Although this code is correct, I suggest you to start writing cleaner code. Here's how this code could be rewritten:
function main() {
const LEVELS = parseInt(readLine(), 10)
let points = []
let sum = 0
// reading values of array points
for(let i = 0; i < LEVELS; i++)
points[i] = parseInt(readLine(), 10)
// calculating sum of elements in array points
for(let i = 0; i < LEVELS; i++)
sum += points[i]
/* You can also merge the above FOR loops
for(let i = 0; i < LEVELS; i++) {
points[i] = parseInt(readLine(), 10)
sum += points[i]
}
*/
console.log(sum)
}
Happy coding!