一个循环,但是全部超时

P1035 [NOIP2002 普及组] 级数求和

Mark_666 @ 2023-01-13 17:38:13

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

by zgy_123 @ 2023-01-13 17:56:30

1/n是整形除法,返回0,在double就是0.000000

要写1/double(n)1.0/n


by Astra0 @ 2023-01-13 17:57:12

@Mark_666

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

by Mark_666 @ 2023-01-13 18:03:20

@Astra0 谢谢两位大佬回答


|