java编程!!用户从键盘输入一个整数n,程序求出n的累加和并输出。(如:1+2+3+4+……+n)

2024-11-01 15:46:33
推荐回答(2个)
回答1:

import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int sum=0;
sum=a*(a+1)/2;
System.out.println(sum);
}
}

回答2:

import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int sum=0;
for(int i=1;i<=a;i++){
sum=sum+i;
}
System.out.println(sum);
}
}