只有第一个测试点对,求大佬帮忙找错

P1035 [NOIP2002 普及组] 级数求和

蛇皮 @ 2020-01-10 22:56:34


#include<stdio.h>
int main()
{
    float k;
    scanf("%f",&k);
    double sum=0;
    for(float i=1;i<=100;i++)
    {
        sum+=(1/i);
        if(sum>k)
        {
            printf("%.0f",i);
            break;
        }
    }
    return 0;
}

by Smallbasic @ 2020-01-10 23:00:19

sum+=(1/i);改成 sum+=(float)(1.0/i);试试


by 蛇皮 @ 2020-01-10 23:11:10

@Smallbasic 还是只有第一个对


by Smallbasic @ 2020-01-11 08:12:43

你把变量类型都改成double?


by Smallbasic @ 2020-01-11 08:13:13

循环次数改大一点可否?


by 蛇皮 @ 2020-01-11 10:56:47

@Smallbasic 换double之后输出全部变成了1


by 蛇皮 @ 2020-01-11 11:02:48

@Smallbasic 刚才输入忘记把f改lf了,现在输出不是1了,但是第一个测试点也错了


by Smallbasic @ 2020-01-11 11:47:43

#include <iostream>

using namespace std;

int main() {
    int n = 0, k;
   double s = 0.0;
   cin >> k;
    while (s <= k) s += (1.0 / (double)(++n));
   cout << n; return 0;
}

by Smallbasic @ 2020-01-11 11:48:49

i不要只循环到100


by Smallbasic @ 2020-01-11 11:49:10

用while(sum <= k)


by 蛇皮 @ 2020-01-11 13:15:35

@Smallbasic 谢谢,过了


|