cheng_de @ 2024-02-18 11:35:17
help me!!! 怎么办?```cpp
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)
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