Математическая матричная программа

В настоящее время я создаю матричную программу, которая может отображать матрицу с нашим вводом, след матрицы, возможность создавать матрицу 2x2 из исходной матрицы, определитель матрицы, подматрицу и иметь возможность удалять строки и столбцы в матрице вот мой код:

#include <stdio.h>

struct matrix
{
    char name;
    int mValues[10][10];
    int nrows;
    int ncols;
};
struct matrix2
{
    char name2;
    int mValues2[10][10];
    int nrows2;
    int ncols2;
};
int main()
{
    struct matrix M1, M2;
    int trace;
    int determinant;

        matrixInput(&M1);
        matrixDisplay(M1);
        matrixTrace(M1, &trace);
        printf("\nThe trace of matrix is %d",trace);

    return 0;
}


void matrixInput(struct matrix *mat)
{
    printf("Please enter a one character name for the matrix, e.g A, B, etc:");
        scanf("%c",&(*mat).name);

    printf("\nEnter # rows of the matrix(<10):\n");
        scanf("%d",&(*mat).nrows);

    printf("Enter # columns of the matrix(<10):\n");
        scanf("%d",&(*mat).ncols);

    printf("\nMatrix %c:\n",(*mat).name);

    FILE *file = fopen("matrix.txt","r");

    for(int x =0; x < (*mat).nrows; x++) {
        for(int y=0; y < (*mat).ncols; y++) {
            fscanf(file, "%d", &(*mat).mValues[x][y]);
        }
    }
    fclose(file);

}

void matrixDisplay(struct matrix mat)
{
    int baris, kolom;

    for(baris = 0; baris < mat.nrows; baris++) {
        printf("Row %d: ", baris);
        for(kolom = 0; kolom < mat.ncols; kolom++) {
            printf("\t%d", mat.mValues[baris][kolom]);
        }
        printf("\n");
    }
    getchar();
    return;
}

void matrixTrace(struct matrix mat, int *trace)
{
    int baris, kolom;
    *trace = 0;
    for(baris = 0; baris < mat.nrows; baris++){
        for(kolom = 0; kolom < mat.ncols; kolom++){
        if (baris == kolom){
    *trace += mat.mValues[baris][kolom];}


    }
    }
}
   void matrixInput2(struct matrix2 *mat2)
{
    printf("Please enter a one character name for the matrix, e.g A, B, etc:");
        scanf("%c",&(*mat2).name2);

    printf("\nEnter row number to start 2x2 matrix, number needs to be between 0 and 2:\n");
        scanf("%d",&(*mat2).nrows2);

    printf("Enter column number to start 2x2 matrix, number needs to be between 0 and 2:\n");
        scanf("%d",&(*mat2).ncols2);
        printf("\nMatrixInput2 %c:\n",(*mat2).name2);
}

вот пример вывода:

Please enter a one character name for the matrix, e.g A, B, etc: A

    Enter # rows of the matrix(<10):
    4
    Enter # columns of the matrix(<10):
    4

    Matrix A:
    Row 0:  1      -15     20     -40
    Row 1:  41     -60     75     -99
    Row 2:  100    -150    2      -14
    Row 3:  21     -39     42     -59

    The trace of matrix is =116

поэтому матрица вызывается в файле .txt, я только что закончил создание отображения матрицы и трассировки, теперь я хочу создать матрицу 2x2 из исходной матрицы, но я не могу снова ввести ввод? программа завершается после вывода, я пытаюсь сделать ее недействительной, но все равно не работает, кто-нибудь может помочь?

Добро пожаловать в Stack Overflow. Пожалуйста, прочтите страницы О и Как спросить в ближайшее время и (что более срочно) прочтите о том, как создать MCVE (минимальный воспроизводимый пример). Непонятно, какая у тебя конкретная проблема

Jonathan Leffler 02.12.2018 01:49

Добавляем пробел scanf(" %c",&(*mat).name);.

chux - Reinstate Monica 02.12.2018 03:34
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
2
89
1

Ответы 1

Теперь я исправил свою проблему, вот обновленный код:

#include <stdio.h>

struct matrix
{
    char name;
    int mValues[10][10];
    int nrows;
    int ncols;
};
struct matrix2
{
    char name2;
    int mValues2[10][10];
    int nrows2;
    int ncols2;
};
int main()
{
    struct matrix m1, *m2;
    int trace;
    int determinant;

        matrixInput(&m1);
        matrixDisplay(m1);
        matrixTrace(m1, &trace);
        printf("\nThe trace of matrix is %d",trace);
        matrixDeterminant(*m2, &determinant);

    return 0;
}


void matrixInput(struct matrix *mat, struct matrix2 *mat2)
{
    printf("Please enter a one character name for the matrix, e.g A, B, etc:");
        scanf("%c",&(*mat).name);

    printf("\nEnter # rows of the matrix(<10):\n");
        scanf("%d",&(*mat).nrows);

    printf("Enter # columns of the matrix(<10):\n");
        scanf("%d",&(*mat).ncols);

    printf("\nMatrix %c:\n",(*mat).name);

    FILE *file = fopen("matrix.txt","r");

    for(int x =0; x < (*mat).nrows; x++) {
        for(int y=0; y < (*mat).ncols; y++) {
            fscanf(file, "%d", &(*mat).mValues[x][y]);
        }
    }
    fclose(file);

}

void matrixDeterminant(struct matrix m1, struct matrix2 *m2,struct matrix2 *mat2, int *determinant)
{

    printf("\n\nFinding the determinant now!");
    printf("\nPlease enter a one character name for the matrix, e.g A, B, etc:");
        scanf("%c",&(*m2).name2);

    printf("\nEnter row number where to start 2x2 matrix, number needs to be between 0 and 2:\n");
        scanf("%d",&(*m2).nrows2);

    printf("Enter column number where to start 2x2 matrix, number needs to be between 0 and 2:\n");
        scanf("%d",&(*m2).ncols2);

    }

void matrixDisplay(struct matrix mat)
{
    int baris, kolom;
    for(baris = 0; baris < mat.nrows; baris++) {
        printf("Row %d: ", baris);
        for(kolom = 0; kolom < mat.ncols; kolom++) {
            printf("\t%d", mat.mValues[baris][kolom]);
        }
        printf("\n");

    }
    getchar();
    return;
}

void matrixTrace(struct matrix mat, int *trace)
{
    int baris, kolom;
    *trace = 0;
    for(baris = 0; baris < mat.nrows; baris++){
        for(kolom = 0; kolom < mat.ncols; kolom++){
        if (baris == kolom){
    *trace += mat.mValues[baris][kolom];}

    }

}
}

Другое дело, что я хочу создать матрицу 2x2 из исходной матрицы и найти определитель матрицы, матрица вызывается из текстового файла, который я создаю, я очень запутался, что мне вводить дальше?

я хочу, чтобы результат был таким:

Please enter a one character name for the matrix, e.g A, B, etc: A

Enter # rows of the matrix(<10):
4
Enter # columns of the matrix(<10):
4

Matrix A:
Row 0:  1      -15     20     -40
Row 1:  41     -60     75     -99
Row 2:  100    -150    2      -14
Row 3:  21     -39     42     -59

The trace of matrix is =116

Finding the determinant now!
Please enter a one character name for the matrix, e.g A, B, etc: B
Enter row number where to start 2x2 matrix, number needs to be between 0 and 2:x

Enter column number where to start 2x2 matrix, number needs to be between 0 and 2:x

The determinant is x for
Matrix B:

Row 0:  x      x  
Row 1:  x      x

Новая матрица 2x2 сохраняется в новой структуре, как я могу это сделать?

Другие вопросы по теме