为什么不行啊

P1035 [NOIP2002 普及组] 级数求和

qumo_04 @ 2024-10-27 10:41:35

#include<iostream>
using namespace std;
int main()
  {
    int k, n=1;
    cin >> k;
    double S =0;
    for (n=1;S<k;n++)
    {
        double a = 1.0/n;
        S +=a; 
    }
    cout << n;
    return 0;
}

by SunXiaolang @ 2024-10-27 10:43:01

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int k,i=1;
    double s=0.0;
    cin>>k;
    while (k>=s){
        s+=1.0/i;
        i++;
    }
    cout<<i-1;
}

@qumo_04 求关


by SunXiaolang @ 2024-10-27 10:45:02

@qumo_04 建议你用while循环,这会比for循环好一点


by a23GCC @ 2024-11-01 18:15:13

#include <bits/stdc++.h>
using namespace std;
int k, n = 1;
double sum = 1;
int main() {
    scanf("%d", &k);
    while (sum <= k) {
        n ++;
        sum += (float)1 / n;
    }
    printf("%d", n);
}

by lym19211247124 @ 2024-11-08 20:24:24

大佬 为什么这个一定要用(double)


|