如何在c++中输出二维数组的偶数列索引并对其进行计算
How to output even column indices of a 2D array and perform calculations on them in c++?
当我在第二次循环后用大括号将循环迭代以相反的顺序(先遍历列,然后遍历行)放在一个2D数组上时,它将输出数组作为原始数组的转置。但是在我输入任何条件或数学函数之后,它没有输出任何东西。
我试图输出只有偶数列索引的元素。我以前解决了这个问题,只打印偶数行的所有列。
//outputs the sum, average, STD of even column indices and any row indices
if ( choice == 30 )
{
{
int sum = 0, c = 0;
float avg, total = 0,std;
cout << "the even column indices elements:" << endl;
for( j=0; j < m; j++ )
{
for( i = 0; i < n; i++ )
if ( i % 2 == 0 )
{
sum = sum + a[i][j];
c++;
cout << a[i][j] << endl;
}
}
avg = float(sum / c);
cout << "the sum of even columns:" << sum << endl;
cout << "the average of even columns:" << avg << endl;
for ( j = 0; j < m; j++ )
{
for( i=0; i < n; i++ )
if ( i % 2 == 0 )
{
total = total + ( a[i][j] * avg ) * ( a[i][j] - avg );
std = float( total / c );
}
}
cout << "the STD of even columns:" << std << endl;
// here is the output of the maximum and minimum of even columns elements
int max = -999, min = 1000;
for( j = 0;j < m; j++ )
{
for( i = 0; i < n; i++ )
if( i % 2 == 0 )
{
if ( a[i][j] > max )
max = a[i][j];
if ( a[i][j] < min )
min = a[i][j];
}
}
cout << "and their max value:" << max << endl;
cout << "and their min value:" << min << endl;
}
}
有几个问题;尽管事实上我不确定这些是否会影响你最后的问题。相反,我希望这些简化可以揭示真正的问题,并防止您在添加print语句和调试时引入其他问题。
首先想到
更多的只是一个优化和简化您重用偶数行解决方案的想法是好的,除了保持行为主更快。(我将把它作为一个练习留给你或其他人提供一个参考,为什么row-major更快,因为在SO上有无数的演示)虽然逻辑相似,但随着元素数量的增加,它将大大优于你的代码
for ( int row = 0; row < num_rows; row++ ) {
for ( column = 0; column < num_cols; col+=2 ) { //notice increment by 2
//do stuff to 2darray[row][column]
}
//another way
for ( column = 0; column < num_cols; col++ ) {
if ( columns % 2 != 0 ) {
continue;
}
//do stuff to 2darray[row][column]
}
}
想
如果max
值最终小于-999或最小值大于1000,那么您的代码将无法工作。查找limits.h
并为您的类型使用数字限制。
为什么?如果你读取的每个值都是<-999就像说它们都是-2000一样,Max仍然会报告为-999。把这个倒过来,用你最小的逻辑来理解问题。
第三认为
同样,这纯粹是性能限制,不应该影响最终答案的正确或错误。你不需要多次遍历数组来做这些事情。你可以一次完成所有的工作。你迭代你的2D数组3次,你只需要遍历它一次,你可以在这一次完成所有的计算。
关于Max被分配为-999的事情,Max是为了检查最大值,而min是检查最小值,所以它应该在每个位置询问列索引,如果是,如果是,它询问最大的值(通常是正的)大于-999,如果小于1000,以此类推。直到我得到最大值和最小值,因为-2000实际上比-999小所以如果我输入它,它应该保持最小值而不是最大值^_^
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 数组中每个段的推力 CUDA 计算索引
- 使用元编程进行高效的索引计算
- 从右到左计算当前索引中的数据结构中的元素数,并打印每个元素的计数
- 如何计算特定的卡组合索引
- 是否有C 功能来计算两个索引之间的距离
- 通过查找重复顶点从 vec3 对象的向量计算索引
- 高效计算两个向量公共元素的索引
- 在计算使用了多少个数组索引的同时,如何填充一个来自用户输入的字符的数组?(使用cin.get)
- 如何使用二进制索引树来计算小于索引值的元素数量
- 类数组总和、索引和计算
- DX11计算着色器只写入一个索引
- 更好的折叠循环索引计算
- 计算树结构中树叶的索引
- 有效地计算字典排序中特定元素的索引
- 对角扁平矩阵的邻域索引计算
- 对于循环数组迭代,if循环测试索引是否为真/假,计算结果不正确
- 最有效的计算字典索引的方法
- 如何在使用thrust::lower_bound()计算VBO索引时克服内存限制
- 如何计算网格索引