为什么这个程序运行不正常? [英] Why this program is not functioning properly ?

查看:86
本文介绍了为什么这个程序运行不正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要打印2D数组(矩阵)的转置。这段代码是打印相同的数组而不是转置矩阵?我在做什么错误?



I want to print transpose of a 2D array (matrix) . This code is printing the same array instead of the transposed matrix ? What mistake am I doing ?

 package assignment1;
    import java.util.* ;
    public class q11
    {
    public static void main (String argc[] )    
    {
    Scanner e = new Scanner (System.in) ;
    int m  , c=0 ;
    int n;     // finding transpose of a matrix .
    
    System.out.println(" enter number of rows ");
    m= e.nextInt() ; // rows
    System.out.println(" enter number of columns");
    n =e.nextInt() ;//columns

    int twod[][] = new int [m][n] ; // 2d array created .   

    System.out.println(" enter array elements ");
 
    for ( int i = 0 ; i<=m-1 ; i++ )
    {
    for (int j=0 ; j <= n-1 ; j++)
    {
    twod [i][j] = e.nextInt() ;
    }
    }
 
    System.out.println(" array is :");
 
    for ( int i = 0 ; i<=m-1 ; i++)
    {
    for (int j=0 ; j <= n-1 ; j++)
    {
    System.out.print(twod[i][j]+"  ");
    }
     System.out.println("");
    }  
    // transposing matrix .
    for (int i =0 ; i<= m-1 ; i++)
    {
     for (int j=0 ; j<= n -1 ; j++)
     {

    c=twod[j][i] ;
    twod[j][i] = twod[i][j] ;       
    twod[i][j] = c ;
  
     }
         }
 
    System.out.println(" transposed array is : ");
    for ( int i = 0 ; i<=m-1 ; i++)
    {
    for (int j=0 ; j <= n-1 ; j++)
    {
    System.out.print(twod[i][j]+"  ");
    }
     System.out.println("");
    }
 
 
}
        
        
        }





我尝试过:



我试图在Netbeans IDE上运行它。



What I have tried:

I have tried to run it on Netbeans IDE .

推荐答案

当矩阵被转置时,也就是说,当使用变量c交换值时,内部for循环必须以j = i + 1开始。如果j最初为0,则交换的值将再次交换,从而产生相同的数组。例如,如果我们取m = 2,n = 2那么它将打印相同的数组。
When the matrix is being transposed, that is , when the values are being exchanged using variable c then inner for loop must start with j=i+1 . If j is initially 0 then the swapped values will again be swapped , resulting in the same array . For example If we take m=2 , n=2 then it will print the same array .


此代码的第一个问题:

The first problem of this code:
// transposing matrix .
for (int i =0 ; i<= m-1 ; i++)
{
    for (int j=0 ; j<= n -1 ; j++)
    {

        c=twod[j][i] ;
        twod[j][i] = twod[i][j] ;
        twod[i][j] = c ;

    }
}



是它将每个元素转置2次。您需要更改循环以仅扫描交换正在执行另一半的矩阵的一半(三角形)。



次要问题,您的代码不处理非方阵。



你不需要转置矩阵就可以简单地以换位形式打印矩阵。


is that it transpose each element 2 times. You need to change the loops to scan only a half of the matrix (triangle) the swap is doing the other half.

Secondary problem, your code do not handled non square matrix.

You don't need to transpose the matrix to simply print it in transposed form.


这篇关于为什么这个程序运行不正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆