如何将数字输出到文件中,所有数字都具有相同的精度
How to output numbers to a file, all of them with the same precision
我有一个双精度的二维数组,我想将这些数字输出到一个文件中(每个二维都是一行(。这不是问题。问题是,输出数字以不同的精度保存在txt文件中。示例:
0 1.173 1.3 2.0744 0 0.13
但我希望他们像:
0.0000 1.1730 1.3000 2.0744 0.0000 0.1300
我试过std::setprecision(6)
和std::cout.precision(6)
,但它们似乎不起作用,或者我用错了它们。这里是我如何将数据输出到文件的简化版本:
std::ofstream ofile("document.dat");
for(int i = 0; i < array_size; i++) {
ofile << array[i][0] << " " array[i][1] << std::endl;
}
正如注释所指出的,您希望使用std::fixed
(以及设置宽度和精度(,因此您可以按照以下一般顺序获得一些东西:
#include <iostream>
#include <iomanip>
#include <vector>
int main() {
std::vector<std::vector<double>> numbers{
{1.2, 2.34, 3.456},
{4.567, 5, 6.78910}};
for (auto const &row : numbers) {
for (auto const &n : row) {
std::cout << std::setw(15) << std::setprecision(5) << std::fixed << n << "t";
}
std::cout << "n";
}
}
结果:
1.20000 2.34000 3.45600
4.56700 5.00000 6.78910
将浮点数与10^n相乘,并将值存储在int变量中,以去除小数。然后将整数除以10^n并将其存储在浮点中,然后就可以将其保存到一个包含n个十进制数字的文本文件中。
相关文章:
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 使用浮点数和双精度数的非常小数字的数学
- 使用设置精度时如何阻止数字向上舍入?
- 如何将数字输出到文件中,所有数字都具有相同的精度
- 如何在 c++ 中添加两个大的双精度数字
- 字符串和双精度的麻烦,等值后再得到一个数字
- 数字小于机器精度的安全算术?
- 避免双精度数字的四舍五入
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 将协议缓冲区中的二进制双精度数组转换为 JavaScript 数字
- 2 个给定数字之间的双精度密度
- 如何将精度设置为C 的100位数字
- 如何在不丢失第一位数字的情况下打印出双精度值
- 试图回合数字时如何避免丧失精度?(C )
- 双精度数字程序意外值
- 在小数点之前设置数字的精度
- 如何将精度设置为一个数字
- 如何存储具有一定精度的数字
- 如何使用boost::multiprecision在运行时更改数字精度