Cure

xiaoxiao2021-03-01  14

题目链接 Given an integer nn, we only want to know the sum of1/k^2 where k from 1 to n.

Input Format

There are multiple cases.

For each test case, there is a single line, containing a single positive integer n.

The input file is at most 1M.

Output Format

The required sum, rounded to the fifth digits after the decimal point.

样例输入

1 2 4 8 15

样例输出

1.00000 1.25000 1.42361 1.52742 1.58044

题目来源

ACM-ICPC 2016 Qingdao Preliminary Contest

第一种代码:

#include<iostream> #include<cstdio> using namespace std; string s; int n,flag; double sum[120005]; void init(){//先进行打表 for(int i = 1;i <= 120000;i++) sum[i] = sum[i - 1] + 1.0 / i / i;//1.0 / (i * i)的话,int 类型必须改成long long 类型 return; } int main(){ init(); while(cin >> s){ n = 0,flag = 0; for(int i = 0;i < s.size();i++){ n = n * 10 + s[i] - '0'; //n += (s[i] - '0') * pow(10,s.size() - i - 1);计算n会越界,如果s.size() = 100、1000 等等, //10 ^100? if(n > 120000){ flag = 1; break; } } if(flag)//超过120000就是固定值 printf("1.64493\n"); else printf("%.5lf\n",sum[n]); } return 0; }

第二种代码:

#include<iostream> #include<sstream> #include<cstdio> using namespace std; int n; string s; double sum[1000005]; void init(){ for(int i = 1;i <= 999999;i++) sum[i] = sum[i - 1] + 1.0 / i / i; return; } int main(){ init(); while(cin >> s){ if(s.size() <= 6){ stringstream x;//字符串流,直接将string类型转化成int类型 x << s; x >> n; printf("%.5lf\n",sum[n]); } else printf("1.64493\n"); } return 0; } #include<iostream> #include<cstring> #include<cstdio> #include<cmath> using namespace std; char s[1200005];//数组一定要开的足够大,否则时间超时,100000不行,具体可以自己去试试 double sum[1000005]; long long int n,arr[1000005]; int main(){ for(long long int i = 1;i <= 1000000;i++){ arr[i] = i * i; sum[i] = sum[i - 1] + 1.0 / arr[i]; } while(~scanf("%s",s)){ n = 0; if(strlen(s) <= 6){ for(int i = 0;i < strlen(s);i++) n += (s[i] - '0') * pow(10,strlen(s) - i - 1); printf("%.5lf\n",sum[n]); } else printf("1.64493\n"); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-4149952.html

最新回复(0)