超,,超时。。。

P1035 [NOIP2002 普及组] 级数求和

Dubeita @ 2017-08-12 12:56:37

#include<iostream>
using namespace std;
int main()
{
    int k;
    double s;
    int i;
    cin >> k;
    i = 1;
    while(s < k)
    {
        s = s + 1 / i;
        i++;
    }
    cout << i << endl;
    return 0;
}

by qzqhb @ 2017-08-12 14:09:31

我的代码:


by qzqhb @ 2017-08-12 14:10:15

#include<bits/stdc++.h>//调用万能库
using namespace std;
int main()
{
    int z,x=0,i,j,m;
    double n=0;
    cin>>z;
    while (n<=z)
    {
        x++;
        n+=1.0/x;    
    }
    cout<<x;
    return 0;
}

by Ch3lly @ 2017-08-14 12:07:02

  1. 你s没有初始化

  2. 求Sn>k 所以循环条件为<=

#include<iostream>
using namespace std;
int main()
{
    int k;
    double s=0;
    double i;
    cin >> k;
    i = 0.0;
    while(s<=k)
    {
        i+=1.0;
        s = s + 1.0/i;
    }
    cout <<i;
    return 0;
}

|