Given an integer n, we only want to know the sum of 1/k2 where k from 1 to n.
Input
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
The required sum, rounded to the fifth digits after the decimal point.
Sample Input
1 2 4 8 15
Sample Output
1.00000
1.25000
1.42361
1.52742
1.58044
题意:
多组输入输出,输入k,输出前1/k^2的和,结果保留小数点后五位
思路:
做法即题意,注意k到1e6之后结果不变,且题目没有给数据范围,即无穷大,用字符串来存。
错误示例:
没有考虑输入的数是无穷大,应该用字符串来存储
结果:Time Limit Exceeded
#include <iostream>
using namespace std;
int main()
{
long long n;
while(scanf("%lld",&n)!=EOF)
{
if(n>1000000) n=1000000;
double sum=0;
for(int i=1;i<=n;i++)
{
sum+=1.0/(1.0*i*1.0*i);
}
printf("%.5lf\n",sum);
}
}
借鉴网站1:
https://www.cnblogs.com/suvvm/p/10034444.html
借鉴网站2:
https://blog.csdn.net/libin66/article/details/52564457
借鉴后自己所写ac代码如下:
代码1:
用string字符串保存无限大数cpp版:
#include <iostream>
#include <string>
using namespace std;
const int maxn=1e6;
double sum[maxn];
int main()
{
string s;
sum[1]=double(1);
for(int i=2;i<=maxn;i++)
{
sum[i]=sum[i-1]+1.0/(1.0*i*1.0*i);
//当然可以写成1.0/((double)i*(double)i),之前没注意到每个数都要转换所以wrong了
}
while(cin>>s)
{
int n=0;
if(s.size()<=6)
{
for(int i=0;i<s.size();i++)//注意string字符串判断长度的方式不同
{
n=n*10+s[i]-'0';
}
printf("%.5lf\n",sum[n]);
}
else
{
printf("%.5lf\n",sum[maxn]);
}
}
}
代码2:
用char字符串保存无限大数C语言版:
#include <stdio.h>
#include <string.h>
double sum[1000010];
char s[30];
int main()
{
sum[0]=0.0;
for(int i=1;i<=1000000;i++)
{
sum[i]=sum[i-1]+1.0/(1.0*i*1.0*i);
}
while(scanf("%s",&s)!=EOF)
{
int len=strlen(s);
if(len>6) printf("%.5lf\n",sum[1000000]);
else
{
int n=0;
for(int i=0;i<len;i++)
{
n=n*10+s[i]-'0';
}
printf("%.5lf\n",sum[n]);
}
}
return 0;
}