njwoodard njwoodard - 8 days ago 4x
C++ Question

Converting array int values to doubles

I have a two-dimensional templated array of integers that I need to perform division on and convert to doubles (in order to create a percentage). It is being passed to my function in the function definition as

int votesarr[4][2]

For each int in the array, I need to run a for loop (I assume) to divide the number by 10,000 and cout the resulting double value.

I'm unsure how to work this with the conversion as well as what I need to pass to the function that I haven't already (if anything).


Based on the extra information you provided in the comments, here is a simple way to just iterate through the int matrix and output the values as floating-point values.

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';

That said, if you are passing votesarr around to different functions then I'd advise to use either:

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


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

to make it simpler, instead of using C-style arrays which decay to pointers when passing to methods (preventing proper use of sizeof to determine dimensions, forcing you to pass the rows, cols to the functions).