elgoog
elgoog

Reputation: 41

C++ function returning 'inf' instead of double

I have the following simple code that computes the nth harmonic number. No matter what I try I keep getting an 'inf' value in the output. How is this possible, even if all my variables are doubles?

#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;
}

Upvotes: 3

Views: 10463

Answers (2)

Petr
Petr

Reputation: 9997

inf is a special floating point value, arising, for example, from division over zero. The latter indeed happens in your program: when n reaches zero, your loop still continues and you try to divide 1.0 over zero.

Change your loop to while (n>0).

Upvotes: 3

slugonamission
slugonamission

Reputation: 9642

Think about this:

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

}

Say I passed in n = 0.0. The loop will execute, yet n = 0 and hence you are performing a division by zero.

Upvotes: 5

Related Questions