请问各位大佬超时了怎么改

P1035 [NOIP2002 普及组] 级数求和

zlh202483023 @ 2024-11-21 16:09:42

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

by Fcersoka @ 2024-11-21 16:23:50

@zlh202483023第10行改为

        sum = sum +double( 1.0 / n);

by zlh202483023 @ 2024-11-21 16:55:32

@Fcersoka从TLE变成WA了还是不太对


by Fcersoka @ 2024-11-21 17:53:48

@zlh202483023

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

by zlh202483023 @ 2024-11-24 09:48:21

@Fcersoka为什么要把n=0,以及写成++n的形式,这块不太理解,我写成从1开始反而不行,谢谢


by woliekiale @ 2024-12-19 09:54:13

@zlh202483023 我个人理解是循环里面先进行n++,再进行求和


|