基本类型:
<span style="font-size:14px;"> 求 1 + 2 + 3 + 4 + 5 + ......+ 99 + 100 的和; </span>
<span style="font-size:14px;">
public class AccumulationDemo {
public static void main(String[] args) {
int sum = 0;//求和
int num = 100;//项数
int temp = 0;//某项的值
for (int i = 1; i <= num; i++) {
temp = temp + 1;
sum = sum + temp;
}
System.out.print(sum);
}
}</span>
<span style="font-size:14px;"><pre name="code" class="javascript">运用累加法处理奇偶异号的累加:</span>
<span style="font-size:14px;">编程求1/1-1/2+1/3-1/4+1/5- … +1/99-1/100
</span>
<span style="font-size:14px;"><pre name="code" class="javascript">public class AccumulationFractionDemo {
public static void main(String[] args) {
double sum = 0; // 总和
double item = 0; // 某一项值
int q = -1;
for (double i = 1; i <= 100; i++) {
q = -q;
item = q / i;
sum = sum + item;
}
System.out.println("1-1/2 +1/3-1/4 + ....+1/99-1/100的和是 :" + sum);
}
}</span>
<span style="font-size:14px;">运用累加法处理重叠数累加:</span>
<span style="font-size:14px;">例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制
</span>
<span style="font-size:14px;"><pre name="code" class="javascript">public class OverlapNumberAccumulationDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请确定a值:");
int a = sc.nextInt();
System.out.print("请确定个数:");
int num = sc.nextInt();
long sum = 0;
long temp = 0;
for (int i = 0; i < num; i++) {
temp = temp * 10 + a;
sum = sum + temp;
}
System.out.print(sum);
}
}</span>
<span style="font-size:14px;">运用累加法处理阶乘累加:</span>
<span style="font-size:14px;"> 题目:求1+2!+3!+...+20!的和
</span>
<span style="font-size:14px;"><pre name="code" class="javascript">public class FactorialSumDemo {
public static void main(String[] args) {
long sum = 0;// 20项的和
int num = 20;// 项数
long temp1 = 1;// 某项的值
for (int i = 1; i <= num; i++) {
int temp2 = 0;
temp1 = 1;
for (int j = 0; j < i; j++) {
temp2 = temp2 + 1;
temp1 = temp1 * temp2;
}
sum = sum + temp1;
}
System.out.print(sum);
}
}</span>