Home > Web Front-end > JS Tutorial > body text

How to find the sum of values ​​from n to m in javascript

青灯夜游
Release: 2021-10-15 16:09:26
Original
3902 people have browsed it

In JavaScript, you can use the for loop and the "=" operator to find the sum of values ​​from n to m, and implement the code "function sum(n,m){var sum=0;for(var i=n ;i

How to find the sum of values ​​from n to m in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript finds the sum of values ​​from n to m

Implementation idea:

  • Find n to The sum of m values ​​is to find the value of n...m, that is, the cumulative result of the range from n to m

  • You can use the for loop to control the cumulative range, fromi= n, i<br>

  • In the for loop body, use = for cumulative calculation

Implementation code:

function sum(n,m){
	var sum=0;
	for(var i=n;i<=m;i++){
		sum+=i;
	}
	console.log(sum);
}
Copy after login

When n is 1 and m is 2, 3, 4, 5, the cumulative sum of values ​​from n to m:

sum(1,2);
sum(1,3);
sum(1,4);
sum(1,5);
Copy after login

How to find the sum of values ​​from n to m in javascript

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to find the sum of values ​​from n to m in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template