为什么算出来总是比正确答案大1啊?

P1035 [NOIP2002 普及组] 级数求和

Mrgteo79c @ 2022-11-07 20:34:36

#include<stdio.h>
int main()
{
    int n,k;
    double s=0;
    scanf("%d",&k);
    for(n=1;s<=k;n++)
    {
        s+=1.0/n;
    }
    printf("%d",n);
    return 0;
}

by Mrgteo79c @ 2022-11-07 20:35:34

求大佬帮帮


by linyukun @ 2022-11-07 20:40:46

@Mrgteo79c s>k不会立马跳出,会n++,最后减掉就行


by __QHY__ @ 2022-11-07 20:50:11

#include<stdio.h>
int main()
{
    int n,k;
    double s=0;
    scanf("%d",&k);
    for(n=1;s<=k;n++)
    {
        s+=1.0/n;
    }
    printf("%d",n);
    return 0;
}

改为:

#include<stdio.h>
int main()
{
    int n,k;
    double s=0;
    scanf("%d",&k);
    for(n=1;s<=k;n++)
    {
        s+=1.0/n;
    }
    n -= 1;                 
    printf("%d",n);
    return 0;
}

就好了。


by Tu_es_trop_belle @ 2022-11-07 21:08:14

@q1haoyu 6


by Mrgteo79c @ 2022-11-08 18:18:50

@q1haoyu 谢谢


by Mrgteo79c @ 2022-11-08 18:19:12

@linyukun 谢谢


|