如何输出2D数组的列索引并在c ++中对它们进行计算?

时间:2014-03-10 21:54:14

标签: c++ arrays

当我第一次将循环迭代以相反的顺序放在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;
    }
}

2 个答案:

答案 0 :(得分:0)

有几个问题;虽然实际上我不确定这些是否会影响你的最终问题。我希望相反,这些简化可能会反映实际问题,并防止您在添加打印语句和调试时引入其他问题。

第一个想法
更多只是优化和简化 你重新使用偶数行解决方案的想法是好的想法,除了它更快地保持行主要。 (我将把它作为练习给你或其他人提供一个参考,为什么行主要更快,因为在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或min小于1000,那么您的代码将无效。查找limits.h并为您的类型使用数字限制。
为什么?如果您读取的每个值都是&lt; -999,比如说它们都是-2000,最大值仍将报告为-999。反转这一点以了解最小逻辑的问题。

第三个想法
同样,这纯粹是性能约束,不应该影响最终的答案是对还是错。 您不需要对阵列进行多次传递即可完成此操作。你可以一次完成所有的工作。你迭代你的2D阵列3次,你只需要经历一次,你可以在那一次通过你的所有计算。

答案 1 :(得分:0)

关于max被指定为-999的事情,max用于检查最大值,min是检查最小值,因此它假设在每个位置询问列索引是否即使那样,如果是,它询问是否有最大的价值(通常是积极的) 大于-999,如果它们小于1000,依此类推......直到我得到最大值和最小值,因为-2000实际上小于-999所以如果我进入那个,它假设保持在最小值而不是最大值^ _ ^