将数组整型值转换为双精度值
Converting array int values to doubles
我有一个二维整数模板数组,我需要对其执行除法并将其转换为双精度(为了创建百分比)。它在函数定义中以
的形式传递给我的函数 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;
}
相关文章:
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 在 c++ 中从双精度转换为字符串
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- C++,遇到将双精度转换为整数的问题
- 在C++中将双精度转换为intptr_t
- 将大双精度转换为科学记数法以用作字符串?
- 了解双精度转换与整数转换中的整数与截断关系
- 将 OLE 自动化日期 (OADate) 双精度转换为结构 tm,而不使用 VariantTime到SystemTime
- 无法在赋值中将"双精度 (*)[4]"转换为"双精度**"
- 将大双精度转换为无符号 int 期间堆栈损坏
- 将双精度转换为本地8位
- 警告从"双精度"转换为"int"
- 如何将双精度转换为浮点指针
- 将双精度转换为整数时出错
- 使用并集将双精度转换为十六进制再转换为双精度
- 是否有可以将每个双精度转换为唯一uint64_t,保持精度和顺序的功能?(为什么我找不到?
- 使用定点表示法将双精度转换为字符串,没有尾随零和机智的冲刺
- 在C++中将双精度转换为字符*/字符串
- 无法将双精度 [] [] 转换为双精度 **