使用小数将Int数组转换为Double Array C ++

时间:2018-09-09 01:10:44

标签: c++ multidimensional-array casting double decimal

例如,我的代码为

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

1 个答案:

答案 0 :(得分:0)

我可以自由地将注释中的发现放入一些代码中:

#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