How to output float value in C++?

242 Views Asked by At

I'm trying to make a program that uses the Taylor Sequence to approximate e. However, I've come across a problem that makes me feel quite noobish at C++. the variable e is a float, but whenever I use cout << e << "\n"; it just outputs 2, not 2.0 or 2.7 or whatever it should be outputting at any point in the code. Here's the main() code:

int main() {
    float e = 1.0;
    int d = 1;
    int counter = 25;
    while(counter>=1){
        counter-=1;
        e+=(1/fact(d));
        d++;
        cout << e << "\n";
    }
}

fact() computes the factorial (!) of a number. When I run the program I get 25 lines that say 2. What am I doing wrong? And I do have #include <iostream> and using namespace std; before the functions.

1

There are 1 best solutions below

1
On

Your division returns an integer and not actually a float. One of the sides of the division has to be a float for the output to be a float.

Changing:

e+=(1/fact(d));

to:

e += (1.0 / fact(d));

Should solve your problem.