PAT甲级1104 Sum of Number Segments (20分) 测试点2感觉不太对,两位数字不同加法有区别

1104 Sum of Number Segments (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,2右边包括他自己有3个数字,所以自身需要乘以3,然后左边有一个数字,所以需要自身乘以 3 乘1 。就这么简单

代码


#include <iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;


int main()
{
    long   N;
    cin>>N;
    double sn[N+1];
    for( long  i=1; i<=N; i++)
    {
        cin>>sn[i];
    }
    double sum=0;
    for(long i=1; i<=N; i++)
    {
        //右边有几个数字,包含自己本身
        long  rightNum=N-i+1;

        //左边有几个数字,不包含自己本身
        long  leftNum=i-1;
        sum+=sn[i]*rightNum;
        sum+=sn[i]*leftNum*rightNum;

        //sum+=sn[i]*(1+leftNum)*rightNum;
        //sum+=sn[i]*leftNum*rightNum+sn[i]*rightNum;
    }
    printf("%.2f",sum);
    return 0;
}

但是测试点2死活过不去,对照其他人的答案,如果

sum+=sn[i]*rightNum;
sum+=sn[i]*leftNum*rightNum;  

就是过不去的
但是换成

sum+=sn[i]*leftNum*rightNum+sn[i]*rightNum;

就能过去了,紧接着我模拟测试了一下,使用下面的代码

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    long n=100000;

    double sum1 = 0, sum2=0;
    for (long i = 1; i <= n; i++) {
        double num=((double)(rand() % (1-0))+ 0 + 1)/10;

        sum1+=num * i * (n - i +1 );
        sum2+= num * i * (n - i );
        sum2 += num * i ;
        if(fabs(sum1-sum2)>0.01)
            n++;
    }

    return 0;
}

设置断点就发现了跑到了断点,如下图
在这里插入图片描述
感觉就是double的小误差,在保留两个小数点的时候刚好差了0.01

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章