为什么输出都是1?

P1035 [NOIP2002 普及组] 级数求和

cheng_de @ 2024-02-18 11:35:17

help me!!! 怎么办?```cpp

include <iostream>

using namespace std; int n = 1, k; double s(int n){ double r = 0; for(int i = 1;i <= n;i++){ r+=1.00/i; } return r; } int main(){ cin >>k; while(s(n)>k){ n++; } cout<<n; return 0; }


by cheng_de @ 2024-02-18 11:36:47

@cheng_de

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

by sunkuangzheng @ 2024-02-18 11:41:06

@cheng_de while(s(n) > k)

所以你的程序只会输出 1,或者死循环。 代码应该改成 `while(s(n) <= k)`

by Vegetableless @ 2024-02-18 11:41:40

s(n) > k 改成 s(n) <= k 另外,你这个代码超时了


by Vegetableless @ 2024-02-18 11:45:38

建议把函数内的循环合并进 while 里。 例如

int main(){
    cin >>k;
    double r = 0.0;
    while(r<=k){ 
        r += 1.00/n;
        n++; 
    }
    cout<<n - 1;
    return 0;
}

by cheng_de @ 2024-02-19 11:15:41

谢谢dalao


|