在 c++ 中,没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?
What is the role of **std::setprecision()** without **std::fixed** in c++?
如教程 http://www.cplusplus.com/reference/iomanip/setprecision/所示
// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main () {
double f =3.14159;
std::cout << std::setprecision(5) << f << 'n'; // prints 3.1416 and not 3.141459 why
std::cout << std::setprecision(9) << f << 'n';
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << 'n';
std::cout << std::setprecision(9) << f << 'n';
return 0;
}
std::cout <<std::setprecision(5( 行不打印 5 个十进制数字,但在设置std::fixed之后,setprecision 按预期工作。为什么?。
没有 std::fixed 的 std::setprecision((的作用是什么?
根据 http://en.cppreference.com/w/cpp/io/ios_base/precision,精度决定打印多少位,而不是打印浮点后的多少位:
std::ios_base::precision
管理浮点数的精度(即生成多少位数字( 点输出
这解释了四舍五入。
是的,使用std::fixed
将更改浮点场精度的解释。根据 http://www.cplusplus.com/reference/ios/ios_base/precision/:
和科学记数法中,精度字段 准确指定小数点后要显示的位数, 即使这包括尾随的小数零。前面的数字 在这种情况下,小数点与精度无关。
精度的含义取决于使用固定格式、科学格式还是默认格式。对于固定格式,它是小数点后的位数。对于科学来说,也是如此——但在点之前总是只有一个数字;指数用于将小数点移动到位置。对于默认格式,精度指定打印的总位数(大致上;它有点复杂(。
有关详细信息,请参阅 http://en.cppreference.com/w/cpp/io/c/fprintf,特别是%f
、%e
和%g
格式说明符的说明(分别适用于固定、科学和默认格式(。std::cout << f
被指定为好像调用printf("%.<precision><format>", f)
(对于第一个近似值;现实再次有点复杂,但细节与手头的问题无关(,其中<precision>
是setprecision
指定的数字,<format>
是f
、e
或g
之一。
std::setprecision()
的行为因所选格式而异。
std::fixed
std::setprecision()
指小数点后打印了多少位数字。在将默认格式更改为std::fixed
之前,将设置std::defaultfloat
,std::setprecision()
设置要打印的总位数,包括小数点之前和之后的位数。
比较:
http://www.cplusplus.com/reference/ios/defaultfloat/
http://www.cplusplus.com/reference/ios/fixed/
这是因为"当floatfield设置为固定时,浮点值是使用定点表示法编写的:该值在小数部分中用与精度字段(精度(指定的数字完全相同,并且没有指数部分 http://www.cplusplus.com/reference/ios/fixed/。
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- "using namespace std;"在C++的作用是什么?
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- std::rethrow(std::exception_ptr) 不起作用
- 无法让"std::enable_if"适用于无作用域枚举
- 将新放置与 std::函数一起使用不起作用
- std::string == 运算符在代码中不起作用
- Cuda 基本程序 (将值写入矩阵和 std:cout 不起作用) ;主功能不启动
- std::函数不起作用,但普通的旧函数指针可以 - 为什么?
- 为什么 std::chrono 在测量循环和编译器优化的并行 OpenMP 的执行时间时不起作用?
- "+=" 操作在类型之间不起作用 std::复杂<double>和__complex__双精度
- std::包含 std::函数回调的多个包装器的向量不起作用
- 初始化 std::initializer_list 通过 std:: 初始化 std::p air 在初始化 std::array 时不起作用?
- std::make_unique_for_overwrite() 对 std::make_unique() 有什么作用?
- 使用 find() 通过 std::set 的迭代器将不起作用。出了什么问题?
- std::flush 不起作用,而 std::endl 可以
- std::lock_guard 似乎提供了线程安全性,尽管作用域块
- 在 c++ 中,没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?