用Java编写一个程序,计算s=1+(1+2)+(1+2+3)+…+(1+2+3+4+5+…+100)。

2024-12-22 20:58:00
推荐回答(2个)
回答1:

public class Sum {

public static void main(String[] args) {

int sum = 0;

for(int i = 1; i <= 100; i++){

int sumI = 0;//calc (1+2+3) for 3
for(int j = 1; j <= i; j++){
sumI = sumI + j;
}

sum = sum + sumI;
}

System.out.println("1+(1+2)+(1+2+3)+…+(1+2+3+4+5+…+100) = " + sum);
}

}

回答2:

public class Sum
{
public static int sum()
{
int j=0;
for(int i=1; i<=100; i++)
{
int m=0;
for(int k=1; k {
m+=k;
j+=m;
}
}
return j;
}
public static void main(String [] args)
{
System.out.println(sum());
}
}