简体   繁体   中英

Creating a Transposed Matrix in C

Creating a Program to print a Transposed Matrix

I'm creating a program in C where the user must define the number of rows and columns of a matrix, then the program must create random numbers and print the Transposed Matrix. I've achieved the first part, but my code isn't working for creating the Transposed Matrix. If it's a squared matrix, it must calculate also the D(mxn) * I(mxn), where D is the matrix and I the Identity matrix. Here`s the code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    unsigned short i, j, m, n;
    int matriz[m][n], mTransposta[m][n], random;
    

    printf("Entre a dimensao m da matriz: ");
    scanf("%hu", &m);

    printf("Entre a dimensao n da matriz: ");
    scanf("%hu", &n);

    printf("A matriz randomizada e:\n");
    for(i = 0; i < m;i++) {
        for(j = 0; j < n;j++) {
            random= rand()%100;
            matriz[m][n]= random;

            printf("%i ", matriz[m][n]);
        }
        printf("\n");
    }
    
    printf("A matriz Transposta e:\n");
    for(i = 0; i < m; i++) {
        for(j = 0; j < n; j++) {
            
            mTransposta[m][n]= matriz[n][m];
        }

        printf("%i ", matriz[m][n]);
    }
    printf("\n");
}

At least these problems

Declared too early

When int matriz[m][n] is declared, m, n do not have assigned values. Declare int matriz[m][n] after assigning m, n .

// int matriz[m][n], mTransposta[m][n], random;

printf("Entre a dimensao m da matriz: ");
scanf("%hu", &m);

printf("Entre a dimensao n da matriz: ");
scanf("%hu", &n);

int matriz[m][n], mTransposta[m][n], random;

Transposed array

This implies mTransposta[m][n] should be mTransposta[n][m]

Print more often

printf("%i ", matriz[m][n]); only prints in an outer loop. Expect that in an inner loop.

Unused mTransposta[m][n]

Code never reads the values in mTransposta[m][n]= .

Other

  • scanf() return values not checked.

  • D(mxn) * I(mxn) code missing.

  • Identity matrix never formed.

  • Printing a space after the last number is poor form. Alternative:

        const char *sep = "";
        for(unsigned j = 0; j < n;j++) {
            matriz[m][n] = rand()%100;
            printf("%s%i", sep, matriz[m][n]);
            sep = " ";
        }
        printf("\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM