如何在c++中输出二维数组的偶数列索引并对其进行计算

How to output even column indices of a 2D array and perform calculations on them in c++?

本文关键字:索引 计算 数列 c++ 输出 二维数组      更新时间:2023-10-16

当我在第二次循环后用大括号将循环迭代以相反的顺序(先遍历列,然后遍历行)放在一个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小所以如果我输入它,它应该保持最小值而不是最大值^_^