How to output float value in C++?

时间:2016-12-26 16:30:29

标签: c++ floating-point cout

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 个答案:

答案 0 :(得分:0)

你的分裂返回一个整数而不是一个浮点数。除法的一个方面必须是浮点数,以使输出成为浮点数。

更改:

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

为:

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

应该解决你的问题。