栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Pat甲-1104

Pat甲-1104

今天写道这道题被坑了一下,思路不难,简单的一道数学题,但是第2个测试点的大数据量有个坑,卡了一段时间,由于思路基本不会出错,应该就是数据类型精度溢出的问题了。通过翻阅大佬们的博客,才想起来double类型在实际大数据量计算时,由于底层二进制实现加减法并不能准确的表达一个浮点数,容易造成double类型无法准确表示,所以最好还是用long long 代替double类型,最后在利用隐式类型转化(long long 类型值 / 1.0)转回浮点数。

1104 Sum of Number Segments 题目

时间限制 200 ms 内存限制 64 MB

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

#include
#include
#include
using namespace std;
int n;
long long res = 0;
int main(){
    scanf("%d", &n);
    for(int i= 0 ;i < n; i++){
        double temp;
        scanf("%lf", &temp);
        //此处对于temp * 1000 ,参考了大佬,可能目的是将double类型的小数点后移,
        //由于题中给定参数恒小于1,此操作可以提高double精度,后续在回复成浮点数时
        //除于等大小浮点数
        res +=(long long) (temp*1000) * (n - i) * (i + 1);
    }
    printf("%.2f", res / 1000.0);
    return 0;
}

但是在测试时,temp仅×1000时能够AC,10000和100都不行,原因暂时还不清楚(难道是参数长度仅到小数点后三位,*1000直接转化为整型操作了?,还是我遗漏了题目的某个要求?)

既然说到类型精度范围了,就简单回顾一下常用类型范围吧(具体的范围请参阅:https://www.runoob.com/cplusplus/cpp-data-types.html)

char-128 ~ +127
short-32767 ~ + 32768
unsigned short0 ~ 65536
int(4 Bytes) 2*10^9
long long(8 Bytes) 9*10^18
double1.7 * 10^308 (8 Bytes)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/720389.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号