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 . 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
Ω
输出一个数组所有连续子串之和之和,可以认为是把所有连续子串中出现的数字加起来。
很显然,我们只需要统计每个数字出现了几次,考虑第 个数(从0开始数),首先以该数字开头的子串共有 个,而以第 个数开头并包含第 个数的连续子串个数都是 ,因此第 个数共计出现 次。最终答案即为
本以为又是水题一道,没想到case 2绿的晃眼。看了半天找不出什么错误,冥冥之中估计又是四舍五入或者是精度的问题。参阅了一些博客之后,发现确实是double的问题。C语言浮点数存储是参照IEEE 754的,简单地说就是由一位符号位(S)和固定位数的阶码(E)、尾数(f)组成 。由于尾数位数有限,因此在阶码较大时低位的数字根本无法存储从而造成了精度的损失,而且数字越大损失越大。有兴趣可以看看纠正测试数据这位同学的博客由一道 OJ 引发的关于 double 类型的一些思考。
🐎
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
double k;
long long ans = 0;
for (int i = 0; i < n; ++i)
{
cin >> k;
ans += (long long)(k * 1000) * (n - i) * (i + 1) ;
}
printf("%.2lf", ans/1000.0);
}