Cout a long double question

So I am working on a C ++ project. I have a var long double type and is assigned a value of type "1.02"

Then I try to use cout to print it and the result is: -0

I've already tried using setprecision and all I found was looking for the problem.

What's the solution for this?

Sample code:

#include <cstdlib>
#include <iomanip>

using namespace std;

int main(int argc, char** argv)
{

    cout.precision(15);
    long double var = 1.2;
    cout << var << endl;
    return 0;
}

      

OS: Windows 8.1 64 bit Compiler: minGW IDE: NetBeans 8.0.2

+3


source to share


4 answers


Seems to be a compiler issue. Take a look here: http://mingw.5.n7.nabble.com/Strange-behaviour-of-gcc-4-8-1-with-long-double-td32949.html



Use printf

or convert the value of your variable to double

before moving on to cout

. (BTW sure you want 80-bit precision?)

+2


source


This is an easier method, but your program worked on my compiler.

#include <cstdlib>
#include <iomanip>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{

    std::setprecision(10);
    long double var = 1.023563457578;
    cout << var << endl;
    return 0;
}

      



Hopefully this helps you understand that your compiler might be having a problem.

Source -> Link

0


source


I don't see anything wrong with the code. I just put it in standard format and it works. Here's the code assuming you've submitted the whole thing.

#include <iostream>

using namespace std;

int main(){
    long double var = 1.0202;
    cout.precision(5);
    cout << var << endl;
}

      

Hope this answers your question.

Edit: Postscript The shorter the better, so I have a better solution (stubborn).

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
    long double var = 1.0202;
    //cout.precision(5);
    cout << setprecision(5) << var << endl;
}

      

I think this is better as it is shorter. I would also recommend using printf if you are doing a more complex decimal element, since printf can choose which variables (if you have several) have decimal numbers or how many.

-1


source


I just figured out the problem. This was including cstdlib instead of iostream.

-3


source







All Articles