计算数组行中的总和
Calculate the sum in the rows of the array
我有一个二维数组a。我需要数组的元素被写入动态数组元素的元素中,记录数组A的行的计算和。使用指针显示动态数组元素。
const unsigned row = 3;
const unsigned col = 4;
int A[row][col];
std::cout << "Input A:n";
for (int index = 0; index < row; ++index)
{
for (int j = 0; j < col; ++j)
{
std::cout << "A[" << index << "][" << j << "]=";
std::cin >> A[index][j];
}
}
unsigned* array = new unsigned[row];
for (int index = 0; index < row; ++index)
{
for (int j = 0; j < col; ++j)
{
array[index] += A[index][j];
}
}
for (unsigned* index = array; *index; ++index)
{
std::cout << *index << "n";
}
但遗憾的是,它不能正常工作。帮我弄清楚。
UPD:
unsigned* end = array + row + 1;
std::cout << "Array:n";
for (unsigned *ptr = array, index = 1; ptr <= end; ++ptr, ++index)
{
std::cout << *ptr << "t";
}
您从未初始化array
,因此此行具有未定义的行为:
array[index] += A[index][j];
你可以简单地修复如果使用:
for (int index = 0; index < row; ++index) {
array[index] = 0;
}
或者:
for (int index = 0; index < row; ++index) {
unsigned sum = 0;
for (int j = 0; j < col; ++j) {
sum += A[index][j];
}
array[index] = sum;
}
最后一个输出也可以更改。您的版本读取超出了界限,因此又是一个未定义的行为。
for (int index = 0; index < row; ++index) {
std::cout << array[index] << "n";
}
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++数据文件、数组和计算赋值
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 有效地计算多维数组的累积和?
- 通过指针算法计算数组长度
- 计算数组重复次数的组合的有效算法,加起来达到给定的总和
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 使用结构数组计算文本文件中单词的出现次数C++
- 使用 2D 数组计算总计、最高价和最低价
- 二维数组:计算行的总和和列的乘积
- 从字符数组计算平均数
- 练习:使用数组计算方差
- 二维数组计算公式
- 从导入的二维数组计算平均值
- 从数组计算数据的c++问题
- 通过二维数组计算文件中的特定记录
- Python模拟显示慢性能,如何加快数组计算速度
- 通过数组计算文本文件数值数据