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

How to add up in javascript

藏色散人
Release: 2021-06-10 15:54:26
Original
7552 people have browsed it

Javascript method to implement accumulation: first create the corresponding js sample file; then implement accumulation through "for(var i = 1;i <= 100;i){sum = i;}" and other methods. Can.

How to add up in javascript

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

How to accumulate in javascript?

JS common algorithm-accumulation/accumulation

Accumulation: Add a series of data to a variable. Finally, the cumulative result is obtained.

empty
var sum = 0;
for(var i = 1;i <= 100;i++){
    sum += i;
}
Copy after login
empty
var h = 100;
var sum = 0;
for(var i = 0;i < 10;i++){
    h = h / 2;
    sum += h;
}
sum = sum * 2 + 100;
Copy after login

Accumulation: Multiply a series of data into a variable to get the cumulative result.

empty
var n = 100;
var result = 1;
for(var i = 1;i <= n;i++){
    result *= i;
}
Copy after login

General form:

Accumulation: v = e;

Accumulation: v *= e;

v represents accumulation Sum/accumulation, e represents the accumulation/accumulation term

Key points of the algorithm:

(1)Initialization

Initialization v:

Accumulation: v = 0;

Accumulation: v = 1;

e initialization, if the accumulation/product term is more complex, it may be decomposed into several sub-terms to be initialized separately. For example, in the problem of calculating pi, the accumulation term is decomposed into The three parts of the symbol, numerator and denominator

(2) The control condition of the loop

One is a fixed number of times, such as the problem of calculating the bounce distance, the problem of calculating the sum of the first 20 items of the sequence, the number of times It is not fixed, but must meet a certain condition: the problem of calculating pi requires that the absolute value of the last term be less than 10-6.

(3) Determine the accumulation/product term

For example, the sum of the first 20 items in a sequence is to use the sum of the current numerator and denominator as the next denominator, and the current denominator as the numerator;

Another example is to find the circumference of pi. The sign is inverted, the denominator is 2, and then the next term is obtained.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to add up 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