求调和级数的和,结果保留3位小数,为什么输入任何数的结果都是1.000?


#include <iostream>
#include <iomanip>
using namespace std;

int NN(int n) {
    int x = 1;
    float sum = 0.000;
    while (x <= n)
        {
            sum += 1 / x;
            x++; 
        }
    cout << setiosflags(ios::fixed) << setprecision(2) << std::fixed << sum;
    return 0;
}
int main() {
    int n;
    while (1) 
    {
        cout << "请输入1—20000之间的一个整数:"; cin >> n; cout << endl;
        if ((n >= 1) && (n <= 20000)) {
            cout << NN(n) << endl; 
            break;
        }
        else { cout << "输入错误,请重新输入" << endl; }
    }
       
}

原因:
是int数与int数相除,精度损失导致的,需要指定除数或被除数为float才行。

附上代码,多种方法,其实目的都是为了声明这个除法运算里最高的精度是float类型,这样就可以避免精度损失了。

 
#include <iostream>
#include <iomanip>
using namespace std;
int NN(int n) {
    int x = 1;
    float sum = 0.000;
    while (x <= n)
        {
            //sum += 1.0 / x; ///< func1 
            sum += ((float)(1))/((float)x); ///< func 2 精度损失导致小数位没了
            //sum += (1)/((float)x); ///< 也是可以的
            //sum += ((float)(1))/(x);
            x++; 
        }
    cout << setiosflags(ios::fixed) << setprecision(2) << std::fixed << sum;
    return 0;
}
int main() {
    int n;
    while (1) 
    {
        cout << "请输入1—20000之间的一个整数:"; cin >> n; cout << endl;
        if ((n >= 1) && (n <= 20000)) {
            cout << NN(n) << endl; 
            break;
        }
        else { cout << "输入错误,请重新输入" << endl; }
    }
}

sum += 1.0/x;

sum+=1.0/x,这样就是小数了

谢谢你们~我还想问问怎么样才能保留3位小数,比如输入5,输出2.283(但是我的代码目前是输入5,输出2.280)请问这是为什么呢?