+ 2
k=6; for(var i=0;i<k;i++){ k+=0.5; } alert(i);
//output= 12 //do u have any explanation?
2 ответов
+ 5
i starts at 0, k starts at 6. Then:
-i=0, k becomed 6+0.5=6.5. On next loops:
-i=1, k=7
-i=2,k=7.5
-.....
-i=11,k=12
-i=12. At this point, i is no longer smaller than k, so the loop exits.
Here is the full list of i and k values for the duration of the program:
0; 6.5
1; 7
2; 7.5
3; 8
4; 8.5
5; 9
6; 9.5
7; 10
8; 10.5
9; 11
10; 11.5
11; 12
12
+ 1
Let's start with the k first.
if you remove the k+=0.5 you'll only get k=i.
But because you are increasing K with 0.5 each round it will go something like this:
K:
6
6.5
7
7.5
etc.
The Boolean statement i < k it means that everytime i increases with one k will increase with 12
So by the time i >= k both will be 12