Java program which sums numbers from 1 to 100

前端 未结 5 1531
别那么骄傲
别那么骄傲 2021-01-29 16:50

I have been recently started learning Java and would want to make code that sums the numbers from 1 to 100 (result would be 5050)

The code should go like 1+2+3+4+5+6+7+8+

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-29 16:53

    Use this code. It will print the value like

    1+2+3.. + 100 = 5050

    public class T35{
    
    public static void main(String[] args) {
        int total=0;
    
        StringBuilder stringBuilder=new StringBuilder();
    
        for(int nmb= 1; nmb<= 100; nmb++){
    
            total+=nmb;
            stringBuilder.append(nmb);
            if(nmb!=100)
            stringBuilder.append("+");
    
        }
        stringBuilder.append(" = "+total);
        System.out.println(stringBuilder.toString());
    }
    
    }
    

提交回复
热议问题