将数组整型值转换为双精度值



我有一个二维整数模板数组,我需要对其执行除法并将其转换为双精度(为了创建百分比)。它在函数定义中以

的形式传递给我的函数
    int votesarr[4][2]

对于数组中的每个int,我需要运行一个For循环(我假设)以将该数字除以10,000并计算得到的双精度值。

我不确定如何与转换一起工作,以及我需要传递给我还没有(如果有的话)的函数。

应该这样做:

int arint[4][2] { {1,2},{ 2,3 },{0,1},{0,2} }; //example intarray arint[x][y];
for (auto &x : arint)for (auto &y : x)std::cout << y / 10000.0 << std::endl;

这将迭代每个arint[x]和每个arint[y],并输出以一行分隔的结果。我只是尽量保持基本的格式。在10.000之后的。0将输出带有小数的结果。

根据您在评论中提供的额外信息,这里有一个简单的方法来迭代int矩阵并将值输出为浮点值。

const std::size_t rows = 4;
const std::size_t cols = 2;
double divisor = 10000.0;
int votesarr[rows][cols]; // fill this somewhere...
for (std::size_t i = 0; i < rows; ++i) {
    for (std::size_t j = 0; j < cols; ++j)
        std::cout << static_cast<double>(votesarr[i][j])/divisor << ' ';
    std::cout << 'n';
}

也就是说,如果你将votesarr传递给不同的函数,那么我建议使用:

std::array<std::array<int, 2>, 4> votesarr; // compile time dimensions known

std::vector<std::vector<int>> votesarr(4, std::vector<int>(2));

使其更简单,而不是使用c风格的数组,当传递给方法时衰减为指针(防止正确使用sizeof来确定维度,迫使您将行,颜色传递给函数)

所以你需要这样写:

double percentage = (double)votesarr[i][j]/10000.0;
std::cout >> percentage >> std::endl;

(double)告诉编译器您要将其强制转换为double类型。您可以使用(char), (int), (customType)等来实现此功能。

然而,除法是一种特殊情况——因为我的10000.0有它"。(int)/(double)被处理为(double)/(double)

#include <iostream>
using namespace std;
int main()
{
        int votesarr[4][2] = {{1,1},{1,1},{1,1},{1,1}};
        double result[4][2];
        double temp;
        for (int i = 0; i <= 3; i++) {
                for (int j = 0; j <= 1; j++) {
                        temp = votesarr[i][j];
                        temp = temp/10000;
                        result[i][j] = temp;
                }
        }
        // I just filled out the arrays by i+j
        //then you need to divide each one by 10,000
        //
        return 0;
}

最新更新