Java write a program to calculate the sum of each of the series:(a)1+4+9+16+...to 20terms.
问题描述:
Java write a program to calculate the sum of each of the series:(a)1+4+9+16+...to 20terms.
答
import java.util.Scanner;
public class Sum {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 创建一个输入容器
Scanner input = new Scanner(System.in);
System.out.println("输入一个开始数:");
int start = input.nextInt();
System.out.println("输入想计算的个数:");
int end = input.nextInt();
Sum s = new Sum();
int sum = s.sum(start,end);
System.out.println("答案是:" + sum);
}
public int sum(int start,int end) {
int sum = 0;
int sum2 = 0;
for (int i = 0; i sum = sum + 1 + 2 * i;
sum2+=sum;
}
return sum2;
}
}