for 循环常见的几种格式

root 站长 2019-12-28 20:36:43 2019-12-28 21:04:25 2

基础格式

1、从1循环到n,每次加1; // for (int i = 1; i <= n; i ++ )   
  
2、从n循环到1,每次减1; // for (int i = n; i >= 1; i -- )   
  
3、从m循环到n,每次加1; // for (int i = m; i <= n; i ++ )    
  
4、从n循环到m,每次减1; // for (int i = n; i >= m; i -- )
  
5、从1循环到n,每次加m; // for (int i = 1; i <= n; i=i+m)
  
6、从n循环到1,每次减m; // for (int i = n; i >= 1; i=i-m)
  
7、从1累加到n; // int sum = 0; for (int i = 1; i <= n; i ++ ) sum = sum + i;
  
8、从1累加到1/n; // double sum = 0; for (int i = 1; i <= n; i ++ ) sum = sum + 1.0/i;

进阶格式

9、3 7 13 21 31 43  // for (int i = 1; i <= n; i ++ ) a[i] = i * (i+1) + 1;
  
10、 计算 1 1 2 3 5 8 ... // a[1] = a[2] = 1; for (int i = 2; i <= n; i ++ ) a[i] = a[i-1] + a[i-2];
  

11 、 计算 1 1 1 2 3 4 6 9 13 19 ... // a[1] = a[2] = a[3] = 1; 
                                    // for (int i = 4; i <= n; i ++ ) a[i] = a[i-3] + a[i-2] + a[i-1];
{{ vote && vote.total.up }}