Why don't I get decimals? (C++)

Performing a code in C++, when using the cout to display a series of "double" numbers on the screen I get as integers (that is, if it is a 6, I would want it to come out 6.00). I've already tried with the setprecision, but it still doesn't work for me. I leave you an example of code:

cout << setw(7) << " h" << ivb[i]-n+1 << " = " << setprecision(2) << b[i];

(ivb it is integer, but b is double).

 1
Author: Wilfredo, 2016-03-29

2 answers

You could try using fixed, indicating that there will be a fixed number of decimal digits after the comma.

cout << setw(7) << " h" << ivb[i]-n+1 << " = " << setprecision(2) << fixed << b[i];

For example:

cout << setprecision (2) << fixed << 2.1;

Would print: 2.10

Similarly, the use of setprecision depends on how the decimal point is formatted: fixed, scientific or floatfmt() (by default).

 1
Author: robe007, 2016-03-29 16:09:46

I see no problem, but it verifies that the value of b[i] is double!, surely that is the drawback. On the other hand, how about increasing the number of decimals?, for example:

   << setprecision(5) << b[i];

#include <iomanip>
#include <iostream>

int main()
{
    double num1 = 3.12345678;
    double num  = 3;

    std::cout << std::setprecision(5) << num1 << std::endl;;
    std::cout << num1 << std::endl;

    std::cout << std::setprecision(5) << num << std::endl;;
    std::cout << num << std::endl;

    return 0;
}

ideone

You can see that although num is double does not show decimals maybe this is what is happening to you, when I say that is double!, on the other hand you can see that without using << std::setprecision(5) it shows you the decimals.

std::cout << num1 << std::endl; //3.12346

If you want them to be displayed in a case similar to that of num you can use:

std::cout << std::fixed << std::setprecision(5) << num << std::endl;
std::cout << num << std::endl;

ideone

 1
Author: Jorgesys, 2016-03-29 17:42:13