How to change/control the output precision in gcc or g++?

你离开我真会死。 提交于 2019-12-25 18:32:35

问题


I have the following piece of code written in c++ and compiled by g++ 4.8.

double x = 0.123456789;
cout << x << endl;

I don't understand why I only get the output

0.1234567

even I define x as long double x. It probably a quite naive question, but can any one give me some hits?


回答1:


Use the precision function or the setprecision manipulator to set the number of significant figures (or decimal places, if you also use fixed).

cout.precision(10);  // 10 significant figures

or

cout << setprecision(10); // also 10 significant figures

or

cout << fixed << setprecision(10);  // always fixed-point format, 10 decimal places

By default, the precision is 6.




回答2:


This page has all you need, namely that you should use the std::setprecision stream manipulator.

double x = 0.123456789;
std::cout << std::setprecision(10) << x << std::endl;


来源:https://stackoverflow.com/questions/27940723/how-to-change-control-the-output-precision-in-gcc-or-g

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