----------------------------------------------------------------
//用递归函数实现
import java.util.Scanner;
class Demo1_DiGui {
public static void main(String[] args) {
while (true) {
System.out.println("请输入一个正整数n,我会为你打印1到n的和");
Scanner sc = new Scanner(System.in);
int sum = getSum(sc.nextInt());
System.out.println("1-n求和的结果是" + sum);
}
}
public static int getSum(int n) {
if (n==1) {
return 1;
}else {
int temp = getSum(n-1);
temp = temp + n;
return temp;
}
}
}
------------------------------------------------------------------------------------------------------------
import java.util.Scanner; //用for循环代替递归函数实现
class Demo1_ForDaitiDigui {
public static void main(String[] args) {
while (true) {
System.out.println("请输入一个正整数n,我会为你打印1到n的和");
Scanner sc = new Scanner(System.in);
int sum = getSum(sc.nextInt());
System.out.println("1-n求和的结果是" + sum);
}
}
public static int getSum(int n) {
int sum = 0;
for (int i=1;i<=n ;i++ ) {
sum = sum + i;
}
return sum;
}
}
|
|