C++ 将数组int值转换为double

C++ 将数组int值转换为double,c++,arrays,function,for-loop,type-conversion,C++,Arrays,Function,For Loop,Type Conversion,我有一个二维的整数模板数组,我需要对其执行除法并将其转换为双精度(以便创建百分比)。它在函数定义中作为 int votesarr[4][2] 对于数组中的每个int,我需要运行一个For循环(我假设)将该数字除以10000,并计算得到的双精度值 我不确定如何进行转换,也不确定我需要传递什么到我还没有传递到的函数(如果有的话)。因此,您需要类似以下内容: double percentage = (double)votesarr[i][j]/10000.0; std::cout >

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

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


我不确定如何进行转换,也不确定我需要传递什么到我还没有传递到的函数(如果有的话)。

因此,您需要类似以下内容:

double percentage = (double)votesarr[i][j]/10000.0;

std::cout >> percentage >> std::endl;
(double)告诉编译器要将其转换为double。您可以使用(char),(int),(customType)等来完成此操作


然而,除法是一种特殊情况——因为我的10000.0在结尾处有“.0”,编译器将其视为双精度,并且根据您在注释中提供的额外信息,(int)/(double)被视为(double)/(double)

,这里有一种简单的方法,可以迭代
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';
}

std::vector-votesarr(4,std::vector(2));
为了使它更简单,不要使用C样式数组,它在传递给方法时会衰减为指针(阻止正确使用
sizeof
来确定维度,迫使您将行、列传递给函数)。

这应该做到:

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;
int-arint[4][2]{{1,2}、{2,3}、{0,1}、{0,2}//阵列arint[x][y]中的示例;
for(auto&x:arint)for(auto&y:x)std::cout
#include
使用名称空间std;
int main()
{
int votesarr[4][2]={{1,1}、{1,1}、{1,1}、{1,1};
双结果[4][2];
双温;

对于(int i=0;我需要这些值吗?还是只输出它们?@Charlie生成的百分比值仅在函数中使用。原始int在另一个函数中输入到数组中,数组被传递到函数中,如我在OP中所示。因此,它们只需要输出,而不需要返回,因为它们不在任何地方使用否则,@ njWooRad对于数组中的每个int,我需要运行for for循环——但您根本没有尝试编写循环,不管您需要循环的原因。<代码> int VoeSARR[ROB] [COLS];.<代码>这不是标准的C++语法,因为它使用VLA。不需要第4行,但否则就行了。谢谢!
std::vector<std::vector<int>> votesarr(4, std::vector<int>(2));
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;
#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;
}