代码神奇,求助

P1035 [NOIP2002 普及组] 级数求和

xiaohy_cd @ 2024-08-06 15:26:35

#include <bits/stdc++.h>
using namespace std;
int main()
{
    double a=1;
    int n=2,k;
    cin >> k;
    for(int i=2;a<=k;i++)
    {
        a+=1/k;
    }
    cout << a;
}

输入1,输出2;输入别的数,不输出?


by lintianhong @ 2024-08-06 15:29:09

第十行应是a+=1/(1.0*k);


by lintianhong @ 2024-08-06 15:29:51

啊,说错了,应是a+=1/(1.0*i);


by lintianhong @ 2024-08-06 15:30:37

还有,不是cout<<i<<endl吗?


by Eva_91418 @ 2024-08-06 15:31:40

很显然

a+=1/k;

应为

a+=1/i;

而且你没有计算出一个最小的 n,使得 S_n>k


by lintianhong @ 2024-08-06 15:31:50

附自己AC代码

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

by xiaohy_cd @ 2024-08-06 15:48:06

@caizhiyan a是总和,要总和大于k才能结束循环。


by caizhiyan @ 2024-08-06 15:49:26

code:

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

by xiaohy_cd @ 2024-08-06 15:53:51

@lintianhong 没AC啊?复制的,一模一样。```

include<bits/stdc++.h>

using namespace std; int main(){ int n,k; double ans=0; cin>>n; while(ans<=n) { k++; ans+=1/(1.0*k); } cout<<k; return 0; }



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

by lintianhong @ 2024-08-06 15:56:46

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

这下应该行了


by xiaohy_cd @ 2024-08-06 15:58:48

@lintianhong 已过,谢谢


| 下一页