Hello, I have this code that creates a random matrix and then calculates the inverse of it. Everything seems to work, but when I check if the inverse matrix is correct, I see that the order and some values are wrong, is anyone able to find the mistake?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void inverse(int r, int c, int* matrix[]);
void vectorb(int r);
int main()
{
srand(time(NULL));
int r;
int c;
printf("define the size of the matrix\n number of rows\n");
scanf_s("%d", &r);
printf("number of columns\n");
scanf_s("%d", &c);
int **matrix = (int**)malloc(r * sizeof(*matrix));
for (int i = 0; i < r; i++)
{
matrix[i] = (int*)malloc(c * sizeof(*matrix[r]));
}
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
matrix[i][j] = rand() % 21 - 10;
printf("%d ", matrix[i][j]);
}
printf("\n");
}
inverse(r, c, matrix);
}
void inverse(int r, int c, int* matrix[])
{
double determinant = 0;
for (int i = 0; i<r; i++)
determinant = determinant + (matrix[0][i] * (matrix[1][(i + 1) % r] * matrix[2][(i + 2) % r] - matrix[1][(i + 2) % r] * matrix[2][(i + 1) % r]));
printf("\nInverse of matrix is: \n\n");
for (int i = 0; i<r; i++){
for (int j = 0; j<r; j++)
printf("%.2f\t", (((matrix[(i + 1) % r][(j + 1) % r] * matrix[(i + 2) % r][(j + 2) % r]) - (matrix[(i + 1) % r][(j + 2) % r] * matrix[(i + 2) % r][(j + 1) % r])) / determinant));
printf("\n");
}
}
Thanks in advance