Java设计题 求1+2+…+100之和,并将求和表达式与所求的和显示出来。

2025-01-04 00:41:24
推荐回答(4个)
回答1:

public class Sum{
public static void main(String args[]){
int sum = 0;
for(int i = 1 ;i<=100 ; i ++){
sum += i;
}
System.out.println("1+2+3+…+100="+sum);
}
}

回答2:

public class Test {

public static void main(String[] args) {

int sum = 0;
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= 100; i++){
sum = sum + i;
sb.append(i + "+");
}

System.out.println(sb.substring(0, sb.length() -1).toString() + " = "+ sum);

}

}

回答3:

public static void main(String[] args) {
int sum = 0;
String str = "";
for(int i = 1;i<101;i++){
sum += i;
if(i !=1){
str += "+"+String.valueOf(i);
}else {
str +=String.valueOf(i);
}
}
System.out.println(str+"="+sum);
}

回答4:

循环语句
long sum=0;
for(int i=1;i<=100;i++){
sum=sum+i;
}
System.out,println("1+2+3+...+99+100="+sum);