正整数 1, 2, 3, ... 被称为自然数。
示例 1: 使用 for 循环的自然数之和
// program to display the sum of natural numbers // take input from the user const number = parseInt(prompt('Enter a positive integer: ')); let sum = 0; // looping from i = 1 to number // in each iteration, i is increased by 1 for (let i = 1; i <= number; i++) { sum += i; } console.log('The sum of natural numbers:', sum);
输出
Enter a positive integer: 100 The sum of natural numbers: 5050
在上面的程序中,提示用户输入一个数字。
parseInt()
将数字字符串值转换为整数值。
for
循环用于查找自然数之和直至用户提供的数。
for
循环从 i = 1 到 100
进行迭代。
在每次迭代中,i 加到 sum 上,i
的值增加 1。
当i变为101时,测试条件为false
,sum等于 0 + 1 + 2 + ... + 100.
示例 2: 使用 while 循环的自然数之和
// program to display the sum of natural numbers // take input from the user const number = parseInt(prompt('Enter a positive integer: ')); let sum = 0, i = 1; // looping from i = 1 to number while(i <= number) { sum += i; i++; } console.log('The sum of natural numbers:', sum);
输出
Enter a positive integer: 100 The sum of natural numbers: 5050
在上面的程序中,提示用户输入一个数字。
while
循环用于求自然数之和。
while
循环继续,直到数字小于或等于 100。
在每次迭代中,i 被添加到 sum
变量中,并且 i 的值增加 1.
当i变为101时,测试条件为false
,sum等于 0 + 1 + 2 + ... + 100.