英文:
Find the sum of the elements from the beginning of an array to the first negative number
问题
我需要使用循环,如“for”循环,找到数组从开头到第一个负数的元素之和。我希望循环将数组中第一个负数之前的所有元素求和并返回总和。
例如,如果我有:
arr = [1, 2, 3, -4, 5]
我需要将“-4”之前的所有元素求和,输出将是:
6
在控制台中打印。
英文:
I need to find the sum of elements from the beginning of the array to the first negative number, using loops, like "for". I want loop to summarize all the elements of array before the first negative number and return the sum.
Like for example if I have:
> arr = [1, 2, 3, -4, 5]
I need to summarize all elements before "-4" , output would be
> 6
to print in the console.
答案1
得分: -2
简单地迭代这些数字,在第一个负数时中断循环。
let arr = [1, 2, 3, -4, 5];
let res = 0;
for (const num of arr) {
if (num < 0) break;
res += num;
}
console.log(res);
英文:
Simply iterate over the numbers and break the loop at the first negative one.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let arr = [1, 2, 3, -4, 5];
let res = 0;
for (const num of arr) {
if (num < 0) break;
res += num;
}
console.log(res);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论