题意:给一个数n,输出从1/(1*1)+1/(2*2)+...+1/(n*n)的值。
思路:打表存到n的数,注意当n很大的时候1/(n*n)越小,那么他就趋近于0,所以当n很大的时候我们输出趋近的值就可以了。注意在实现的时候不能直接算1/(n*n),需要1/n/n。因为这个数可能很大,所以我们用字符串读入,保留5位小数,那我们打表打到1e6就可以了。
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
const int N=1e6+5;
typedef long long ll;
double a[N];
string s;
void init(){
double sum=0;
for(int i=1;i<=1e6;i++){
sum+=(double)(1.0/i/i);
a[i]=sum;
}
}
void sove(){
string s;
while(cin>>s){
if(s.size()>=7){
printf("%.5f\n",a[1000000]);
}else{
int t=stoi(s);//将字符串转换为整数的函数
if(t>=1000000){
printf("%.5f\n",a[1000000]);
}else printf("%.5f\n",a[t]);
}
}
}
int main(){
int t=1;
init();
while(t--){
sove();
}
return 0;
}