在c++中控制浮点数的精度
Control the Precision of float number in a C++
我试图控制我在字符串中添加的数字数量,但我无法控制它,因为我正在打印字符串数组。
float loads[n] = { 1,2,3,0.05,1,2,3,0.5,1,2,3,3,1,2 };
string print[nBits] = { "" };
int n=14;
int BB;
.
.
.
void main(){
for (int j = 0; j < nBits; ++j)// 2^n
{
for (int i = 0; i < n; ++i) // n
{
BB = arr[j][i];
R = loads[i];
if (BB == 1) {
print[j]+="" +std::to_string(loads[i])+"//";
}
}
}
但我最终得到一个字符串数组,看起来像这样:
0.050000//3.000000//…
在将浮点数添加到字符串之前,是否有任何方法可以控制其精度?
(所以我可以有一个结果字符串控制固定数量的数字,而不是)
0.05//3.00//…
将std::stringstream
与std::fixed
、std::setprecision(n)
一起使用
你可以使用标准的流机制:
您可以使用ostream生成字符串:
#include <ostream>
#include <sstream>
#include <iomanip>
std::ostringstream stream;
for(...) {
stream << loads[i] << "//";
}
std::string str = stream.str();
这个想法是生成一个流,你也可以流字符串。然后,您可以使用stream.str()
从中生成std::string
。流具有如何转换数字的默认值。您可以使用std::setprecision
和std::fixed
以及其他变量来影响这一点(有关更多信息,请参阅c++ stdlib参考)。
使用std::setprecision
和std::fixed
.
std::ostringstream stream;
// set the precision of the stream to 2 and say we want fixed decimals, not
// scientific or other representations.
stream << std::setprecision(2) << std::fixed;
for(...) {
stream << loads[i] << "//";
}
std::string str = stream.str();
你可以在这里找到另一个例子。
sprintf
你总是可以用C的方式,使用sprintf
,尽管这是不鼓励的,因为你必须提供一个正确长度的缓冲区,例如:
char buf[50];
if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
std::string s(buf);
}
相关文章:
- 使用浮点数和双精度数的非常小数字的数学
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 位设置为浮点数或双精度值 c++
- 为什么浮点数的矢量化比双精度更有效?
- 在C++中序列化浮点数/双精度,编译为 WebAssembly
- 为什么编译器接受具有长双精度文本的浮点数的初始化?
- C++ 警告:在一个声明中将截断从双精度初始化为浮点数,但在另一个声明中则不初始化
- 在 OpenCL 内核中实现半精度浮点数据类型
- 如何随机化双精度/浮点数据类型? C++
- 提升多精度浮点数128:标准::exp错误:'no matching function for call'
- 如何提高计算浮点数的精度?
- atof() 返回浮点数而不是双精度
- 如何以最大精度(C++)将uint64_t转换为0到1之间的双精度/浮点数?
- 单个精度浮点数上的第 24 个分数位在哪里?IEEE 754
- 在C++中实现半精度浮点数
- C++双精度/浮点数的内部表示
- 清除单个精度浮点数的位
- 将双精度浮点数舍入到最接近且更大的浮点数
- 如何判断双精度浮点数是否可以安全地存储为单精度浮点数
- 用于高精度浮点数的c++类型