Java,求1到100的累加值
阿新 • • 發佈:2019-01-08
public class SumDemo {
//1到100相加
public static void main(String[] args) {
System.out.println("方法1:"+sum1());
System.out.println("方法2:"+sum2());
System.out.println("方法3:"+sum3(100));
}
//方法1 while迴圈
public static int sum1(){
int sum = 0;
int i = 0;
while (i<=100){
sum+=i;
i++;
}
return sum;
}
//方法2 for迴圈
public static int sum2(){
int sum = 0;
for(int i=0;i<=100;i++){
sum+=i;
}
return sum;
}
//方法3 遞迴
public static int sum3(int num){
if (num==1){
return 1;
}
else{
return num+sum3(num-1);
}
}
}
輸出結果:
方法1:5050
方法2:5050
方法3:5050