哪位dalao帮忙看一下,全TLE了

P1035 [NOIP2002 普及组] 级数求和

NineBirds_j @ 2023-07-29 15:11:16

#include<bits/stdc++.h>
using namespace std;
int main(){
    int k,s=1,n=1;
    scanf("%d",&k);
    while(2>1){
        n=n+1/s;
        s=s+1;
        if(n>k){
            printf("%d",n);
            break;
        }
    }
}

帮忙看一下 ,全超时了
求求了


by rabbitohh @ 2023-07-29 15:13:04

while(2>1)


by MRevolution @ 2023-07-29 15:13:42

有没有一种可能,可以用for循环,比较快速


by rabbitohh @ 2023-07-29 15:18:11

我猜您是想这么写

#include<bits/stdc++.h>
using namespace std;
int main(){
    int k,n=1;
    double s=0;
    scanf("%d",&k);
    while(k>=s){
        s=s+(1.0/n);
        if(s>k)
        {
            printf("%d",n);
            break;
        }
        n=n+1;
    }
}

by winner_0207_AFO @ 2023-07-29 15:22:42

emmm

#include <bits/stdc++.h>
using namespace std;
int n,k;
double sum;
int main(){
   cin>>k;
    while(sum <= (double)k){
        n++;
        sum += 1.0 / (double)n;
    }
    cout<<n;
    return 0;
}

by NineBirds_j @ 2023-07-29 15:55:06

@MRevolution 我试过了,不行
别问我怎么知道的


by NineBirds_j @ 2023-07-29 15:56:53

@rabbitohh 谢谢 dalao


by Coffee_Moew @ 2023-08-01 13:24:29

@LeeMini 1/s是整型,默认向下取整,除了第一项,其他全是0,样例也过不了,要乘1.0


by NineBirds_j @ 2023-08-02 13:28:08

@Coffee_Moew 哦,谢谢


by Aurora09 @ 2023-08-16 09:40:32


#include<bits/stdc++.h>
using namespace std;
int main(){
    int k,s=0;
    double n=0;
    scanf("%d",&k);
    while(n<=k){
        s=s+1;
        n+=1.0/s;
    }
    cout<<s;
}

by Andy_hpy @ 2023-09-13 15:23:37

while(2>1)改成while(true)或是for(;;)


|