简体   繁体   English

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

[英]C++ function returning 'inf' instead of double

I have the following simple code that computes the nth harmonic number. 我有以下简单的代码可以计算n次谐波数。 No matter what I try I keep getting an 'inf' value in the output. 无论我尝试什么,我都会在输出中不断获得“ inf”值。 How is this possible, even if all my variables are doubles? 即使我所有的变量都是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;
}

Think about this: 考虑一下:

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

}

Say I passed in n = 0.0 . 假设我传入了n = 0.0 The loop will execute, yet n = 0 and hence you are performing a division by zero. 循环将执行,但n = 0 ,因此您正在执行除以零的操作。

inf is a special floating point value, arising, for example, from division over zero. inf是一个特殊的浮点值,例如,由零除而产生。 The latter indeed happens in your program: when n reaches zero, your loop still continues and you try to divide 1.0 over zero. 后者确实发生在程序中:当n达到零时,循环仍然继续,并且您尝试将1.0除以零。

Change your loop to while (n>0) . 将循环更改为while (n>0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM