Cout long double issue

℡╲_俬逩灬. 提交于 2019-12-01 08:01:27

It seems to be a problem with compiler. 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 a value of your variable to double before passing to cout. (BTW are sure you need 80-bit precision?)

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

I hope this helps you see that your compiler might actually have a problem.

Source - > Link

bobtheboy

I see nothing wrong at all in the code. I just put it into a standard format and it works. Here is the code assuming what you posted is the entire thing.

#include <iostream>

using namespace std;

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

I hope this answers your question.

Edit: P.S. Shorter, the better, so I have a better solution (opinionated).

#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 one is better since it is shorter. I would also recommend using printf if you are doing more complex decimal stuff since printf can choose which variables (if you have multiple) have decimals or how much.

nervousDev

I just figured out the problem.. It was the include of cstdlib instead of iostream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!