在java中 将1到100累加起来怎么做?

2025-01-19 20:33:30
推荐回答(5个)
回答1:

很简单,如下:

public class Add {

 public static void main(String[] args) {

  int num = 0;

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

   num += i;//等价于num = num + i;

  }

  System.out.println("1到100累加和为:" + num);

 }

}

回答2:

package other;
public class Test {
public static void main(String[] args) {
Test test = new Test();
int maxNum = 100;//累加终值
System.out.println(test.addNum(0,1,maxNum));
System.out.println(test.add(maxNum));
}
/**
* 递归方式进行1到100累加
* @param num1
* @param num2
* @param maxNum
* @return
*/
public int addNum(int num1,int num2,int maxNum){
int sum = 0;
sum = num1 + num2;
if(num1+2 > maxNum){
return sum;
}else if(num2+2 > maxNum){
return sum + num1 + 2;
}else{
return num1 + num2 + addNum(num1+2,num2+2,maxNum);
}
}
/**
* 循环方式进行累加
* @param maxNum
*/
public int add(int maxNum){
int sum = 0;
for(int i = 0;i <= maxNum;i++){
sum = sum + i;
}
return sum;
}
}

回答3:

public class Test {

public static void main(String[] args) {

int sum = 0;

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

System.out.println("1+2+3+...+100 = " + sum);

}

//海伦公式求面积

public static double getTripleArea(double[] ary ){
double a = ary[0];
double b = ary[1];
double c = ary[2];

double p = (a + b + c) / 2;
double area = Math.sqrt(p * (p -a) * (p - b) * (p - c));;
return area;
}

}

回答4:

简单,高效率的方法:
public static void main(String[] args){
//利用公式(1+100)*50
int a=1,b=100;
System.out.println("1+2+3+..+100 = " + (a+b)*50);
}

回答5:

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

System.out.println(num); //输出结果为5050