简体   繁体   English

如何在gcc或g ++中更改/控制输出精度?

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

I have the following piece of code written in c++ and compiled by g++ 4.8. 我有以下用c ++编写并由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 . 即使我将x定义为long double x It probably a quite naive question, but can any one give me some hits? 这可能是一个非常幼稚的问题,但有人可以给我带来一些帮助吗?

This page has all you need, namely that you should use the std::setprecision stream manipulator. 此页面有你所需要的,即你应该使用std::setprecision流处理器。

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

Use the precision function or the setprecision manipulator to set the number of significant figures (or decimal places, if you also use fixed ). 使用precision函数或setprecision操纵器设置有效数字的数量(如果还使用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. 缺省情况下,精度为6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM