「1104」Sum of Number Segments

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 类型的一些思考

想在本题内解决这个问题并不难,只要将double左移3位转存long long,最后再/1000.0即可,不过这只能算缓兵之计。如果想要做到0误差可能就需要实现一个大数类,这不经让我想起了大一做的个大作业:高精度实数运算,是用链表实现了一个大数类,算是用空间换精度,闲来无事可以瞅瞅。


🐎

#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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值