c++求救

P1035 [NOIP2002 普及组] 级数求和

yinbe @ 2022-08-25 10:01:41

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

by tbdsh @ 2022-08-25 10:09:02

这题要用for循环写,条件留空,然后在循环里写:

  if (sum > k){
   cout << i <<endl;
   break;
  }

by tbdsh @ 2022-08-25 10:10:43

你的问题好像是他一直死循环,你把这个:

s=s+1/n;

改成这个试试:

s=s+1.0/n;

by tbdsh @ 2022-08-25 10:11:27

然后输出时要输出N-1


by Jim777 @ 2022-08-25 10:40:29

for(int i=0;S<=k;i++){                S=S+1.0/n;
        n++;
}
cout<<n-1;
return 0;

}


by Jim777 @ 2022-08-25 10:41:38

for循环这样写


by Jim777 @ 2022-08-25 10:43:23

s=s+1.0/n这里要换行(我忘了)


by yinbe @ 2022-08-26 10:13:19

谢谢各位大佬的帮助


|