求大佬拯救一下我的代码

P1035 [NOIP2002 普及组] 级数求和

逆袭疾风 @ 2020-01-11 14:30:54

#include<stdio.h>
int main()

{
        int k; double s, n;
        n = 0; s = 0;  
        scanf("%d", &k);
        do
        {   n++;
            s = s + (1.0/n);

        } while (s <= k);
        printf("%d", n);
        return 0;
}

哪里错了QAQ


by andyli @ 2020-01-11 14:32:57

@逆袭疾风 n不要用double,用int


by andyli @ 2020-01-11 14:33:41

@逆袭疾风 如:

#include<stdio.h>
int main()

{
        int k; double s;
        int n;
        n = 0; s = 0;  
        scanf("%d", &k);
        do
        {   n++;
            s = s + (1.0/n);

        } while (s <= k);
        printf("%d", n);
        return 0;
}

by zhy137036 @ 2020-01-11 14:36:50

%d输出double会有玄学问题


by 逆袭疾风 @ 2020-01-11 14:46:02

@andyli 谢谢!


by 逆袭疾风 @ 2020-01-11 14:46:19

@zhy123456 谢谢!


by 逆袭疾风 @ 2020-01-11 14:51:16

@andyli 另外是不是printf("%lf",n)不合题意0.0


by wheneveright @ 2020-01-11 14:58:30

@逆袭疾风 printf("%.0lf",n)也可以


by wheneveright @ 2020-01-11 14:59:03

@Q_D_S %.xlf 就是保留x位小数


|