PAT A1104測試點2錯誤修正方法

等風來fighting~發表於2020-10-14

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

測試點2出錯原因:新改的測試資料需要long double型,

解決方法:將輸出值定義為long double就行,輸入輸出格式符使用“%llf”

另外,注意i起始位置不一樣,後面的處理演算法需要對應平移,具體如下:

1、對於i從位置0開始,有關係ans += q[i] * (n - i) * (i + 1)成立;
2、而對於i從位置1開始,則有關係式ans += q[i] * i * (n + 1 - i)成立。

#define _CRT_SECURE_NO_DEPRECATE //定義CRT安全無棄用
#include<iostream>
using namespace std;
const int N = 100010;
double q[N];
int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%lf", &q[i]);
	}
	long double ans = 0;
	for (int i = 0; i < n; i++) {
		ans += q[i] * (n - i) * (i + 1);
		//ans += q[i] * i * (n + 1 - i);
	}
	printf("%.2llf\n", ans);
	return 0;
}

說明:原文參考部落格:https://blog.csdn.net/Kaisers_Q/article/details/108241539?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf

相關文章