求大佬看看哪错了

P1035 [NOIP2002 普及组] 级数求和

wuqikeqing @ 2023-03-31 16:23:53

#include<stdio.h>
int main(){
    double a,sn=0.0,k=1.0;
    scanf("%d",&a);
    if(sn<=a){
        sn=sn+1/k;
        k=k+1;
    }else{
        printf("%d",k);
    }

    return 0;
}

by lanmengfei @ 2023-03-31 16:28:23

要循坏


by Claire0918 @ 2023-03-31 16:29:28

@wuqikeqing 应使用 while 循环


by wuqikeqing @ 2023-03-31 16:32:34

@lanmengfei 反应过来了,脑子抽了,谢谢大佬


by lanmengfei @ 2023-03-31 16:36:07

@wuqikeqing

帮你改一下

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

by wuqikeqing @ 2023-03-31 17:02:06

@lanmengfei 非常感谢


|