请问这个哪出错了?

P1035 [NOIP2002 普及组] 级数求和

yuhaocheng @ 2020-01-12 14:50:33

请问这个哪出错了?

C++:

#include<iostream>
using namespace std;

int k;
int n = 1;
int i;
int s = 0;

int main() {
    cin >> k;
    while(true) {
        for(i = 1;i <= n;i += 1) {
            s += 1/i;
        }
        if(s > k) {
            break;
        }
        else {
            n += 1;
        }
    }
    cout << n;
}

by CSP_Sept @ 2020-01-12 14:52:40

s += 1/i;

应改为:

s += 1.0/i;

by CSP_Sept @ 2020-01-12 14:52:49

@yuhaocheng


by CSP_Sept @ 2020-01-12 14:54:01

要不然会向下取整的

如:

1/10=0
21/8=2

by CSP_Sept @ 2020-01-12 15:42:46

@yuhaocheng


by CSP_Sept @ 2020-01-12 18:22:46

@yuhaocheng


by yuhaocheng @ 2020-01-12 19:09:13

谢谢


|