累加法

基本类型:

<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>


 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值