Pat甲-1104

Pat甲-1104,第1张

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 ~ +127short-32767 ~ + 32768unsigned short0 ~ 65536int(4 Bytes) 2*10^9long long(8 Bytes) 9*10^18double1.7 * 10^308 (8 Bytes)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5716703.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存