将Int数组转换为带有小数的双数组C ++

问题描述 投票:-2回答:1

例如,我有代码

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

c++ multidimensional-array casting double decimal
1个回答
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');
    }
}

Example Output:

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
© www.soinside.com 2019 - 2024. All rights reserved.