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

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