将 int 数组转换为带有小数C++的双精度数组

Cast an Int Array into a Double Array C++ with Decimals

本文关键字:数组 小数 C++ 双精度 int 转换      更新时间:2023-10-16

例如,我有

int 结果[11][2],我需要将这些值转换为具有指定十进制值的双精度 d[11][2],例如左侧 4 位。我似乎已经通过在数组外部抛出一个(双精度(来投射双精度,在我的一个算法之前。我似乎无法弄清楚如何移动十进制值占位符,并且已经搜索了这个网站和C++图书馆试图找到答案。我在向量上看到了一些东西,但我不确定这些是什么。我的一些最终答案是整数,例如 100,有些是小数,例如 13.33。

我冒昧地将注释中的发现放在一些代码中:

#include <iostream>
#include <iomanip>
#include <algorithm>
// only for dirty random numbers:
#include <ctime>
#include <cstdlib>
int main()
{
std::srand(static_cast<unsigned>(std::time(nullptr)));
int foo[11][2];
// some data:
for (auto &f : foo)
for (auto &i : f)
i = rand();
// copy to an array of arrays of doubles:
double bar[11][2];
std::copy(&foo[0][0], &foo[0][0] + 11 * 2, &bar[0][0]);
// some calculation:
for (auto &b : bar)
for (auto &d : b)
d *= 100. / rand();
// output:
for (auto &b : bar) {
for (auto &d : b)
std::cout << std::fixed << std::setw(8) << std::setprecision(4) << d << 't';
std::cout.put('n');
}
}

示例输出:

255.3750        155.6058
45.7636        164.7974
50.4983         99.8548
108.2106         90.2723
42.8402         86.1336
241.4214        802.7950
175.9784         86.9273
11.9571        741.2245
95.0048        225.1073
84.7645        389.8197
39.6910          3.0909