#?

P1035 [NOIP2002 普及组] 级数求和

zz101206 @ 2022-07-19 14:20:03


#include<bits/stdc++.h>
using namespace std;
int k,n=1,ans=0,i;
int main(){
    cin>>k;
    for(i=1;;i++){
        ans=ans+n/i;
        if(ans>k){
            break;
        }
    }
    cout<<i;
}

by zhangruozhong @ 2022-07-19 14:29:16

n/i默认是整数,要换double


by zz101206 @ 2022-07-19 15:50:55

@zhangruozhong

#include<bits/stdc++.h>
using namespace std;
int k,ans=0,i;
double n=1;
int main(){
    cin>>k;
    for(i=1;;i++){
        ans=ans+n/i;
        if(ans>k){
            ans=i;
            break;
        }
    }
    cout<<ans;
}

超时了?


by zhangruozhong @ 2022-07-19 16:25:21

ans也要是double


by zhangruozhong @ 2022-07-19 16:27:24

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    double x=0;
    long long ans=0;
    for(int i=1;;i++)
    {
        double l=1.0/i;
        x+=l;
        ans++;
        if(x>n)break;
    }
    cout<<ans;
}

|