C++ 函数返回 'inf' 而不是 double

标签 c++ floating-point double

我有以下计算 n 次谐波数的简单代码。无论我尝试什么,我都会在输出中得到一个“inf”值。这怎么可能,即使我所有的变量都是 double 的?

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

double harmonic(double n){
    double h = 0.0;
    while(n >= 0){
        h = h + (1.0/n);
        n = n-1.0;

    }
    return(h);
}
int main(int argc, char** argv) {
    double n;
    cout << "enter an integer: ";
    cin >> n;
    cout << "The " << n << "th harmonic number is: ";
    cout << harmonic(n) << endl;

    return 0;
}

最佳答案

想想这个:

while(n >= 0){
    h = h + (1.0/n);
    n = n-1.0;

}

假设我传入了 n = 0.0。循环将执行,但 n = 0 因此您正在执行除以零。

关于C++ 函数返回 'inf' 而不是 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32587421/

相关文章:

c++ - QtSql连接

c++ - SSE、内在函数和对齐

java - 从文件中删除重复行

将 int 转换为 float 到 hex

Java - 将 double /浮点四舍五入到小数点后两位时出现意外结果

c++ - 在 C++ 中将 double 转换为 int 而不会出现向下舍入错误

c++ - 为什么我的 .cpp 文件没有被处理?

c# - 如何将 float 舍入到最接近的 n 倍数?

c# - 为什么 DateTime 到 Unix 时间使用 double 而不是整数?

c# - 对于需要精确到 .00001 的翻译,Decimal 或 Double 会更好吗?