注意:100之和為5050
普通for循環:
1
2
3
4
5
6
7
8
9
|
public class HundredSum { public static void main(String[] args){ int x= 0 ; for ( int i= 1 ;i<= 100 ;i++){ x=x+i; //x+=i; } System.out.print(x); } } |
while循環:
1
2
3
4
5
6
7
8
9
10
|
public class HundredSum { public static void main(String[] args){ int x= 0 ; int i; while (i<= 100 ){ x=x+i; //x+=i; i++; } System.out.print(x); } } |
do-while循環:
1
2
3
4
5
6
7
8
9
10
|
public class HundredSum{ public static void main(String[] args){ int i= 0 ,x= 0 ; do { x=x+i; //x+=i; i++; } while (i<= 100 ); //先循環do語句塊,再執行while,不滿足while條件則跳出循環 System.out.print(x); } } |
以上就是本次整理的3種常用的求和方法,感謝大家對服務器之家的支持。
原文鏈接:https://www.idaobin.com/archives/333.html