PAT A1104 Sum of Number Segments (20 分)/B 1049 数列的片段和 (20 分)

75 篇文章 0 订阅

PAT A1104 Sum of Number Segments (20 分)/B 1049 数列的片段和 (20 分)

Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For example, given the sequence { 0.1, 0.2, 0.3, 0.4 }, we have 10 segments: (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) and (0.4).

Now given a sequence, you are supposed to find the sum of all the numbers in all the segments. For the previous example, the sum of all the 10 segments is 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N, the size of the sequence which is no more than 10^ 5​ . The next line contains N positive numbers in the sequence, each no more than 1.0, separated by a space.

Output Specification:
For each test case, print in one line the sum of all the numbers in all the segments, accurate up to 2 decimal places.

Sample Input:
4
0.1 0.2 0.3 0.4
Sample Output:
5.00
1049 数列的片段和 (20 分)
给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列 { 0.1, 0.2, 0.3, 0.4 },我们有 (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4) 这 10 个片段。

给定正整数数列,求出全部片段包含的所有的数之和。如本例中 10 个片段总和是 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。

输入格式:
输入第一行给出一个不超过 10^ 5​ 的正整数 N,表示数列中数的个数,第二行给出 N 个不超过 1.0 的正数,是数列中的数,其间以空格分隔。

输出格式:
在一行中输出该序列所有片段包含的数之和,精确到小数点后 2 位。

输入样例:
4
0.1 0.2 0.3 0.4
输出样例:
5.00
以下是AC的代码:

#include<cstdio>
int main(void){
	int n;
	scanf("%d",&n);
	long double ans=0.0, temp;
	for(int i=1;i<=n;i++){
		scanf("%Lf",&temp);
		ans+=temp*(long double)(n-i+1)*i;
	}
	printf("%.2Lf",ans);
	return 0;
}

思路:
这道题是找规律的题,在做的过程中规律非常容易找,第 i 个数字出现的次数是 (n-i+1)*i;那么直接累加输出就可以了。
这样一做你会发现第4个或者第3/4个测试点都是答案错误。第一个修改的地方是:

		ans+=(long double)(n-i+1)*i*temp;

改成:

		ans+=(long double)temp*(n-i+1)*i;

这里涉及到隐式格式转换。
另外用了double 还是不能完全通过,改成 long double 以后才通过。这里需要注意 long double 在scanf 和 printf里需要用 Lf.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值