printf("ho_tari\n");

과제 - 행렬 곱셈 구현 본문

대학교 2학년 1학기/데이터구조

과제 - 행렬 곱셈 구현

호타리 2023. 9. 4. 11:35
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main(void)
{
	int a;
	int** A = { 0, };
	int** B = { 0, };
	int** C = { 0, };
	int i, j;
	int x, y;
	int b, c, d;
	int sum;

	srand((unsigned int)time(NULL));

	printf("input matrix size= ");
	scanf_s("%d", &a);

	A = (int**)malloc(sizeof(int*) * a);

	printf("\nFirst matrix = \n");
	for (i = 0; i < a; i++)
	{
		A[i] = (int*)malloc(sizeof(int) * a);
	}

	for (i = 0; i < a; i++)
	{
		for (j = 0; j < a; j++)
		{
			A[i][j] = rand() % 10 + 1;
		}
	}

	for (i = 0; i < a; i++)
	{
		for (j = 0; j < a; j++)
		{
			printf("%3d", A[i][j]);
		}
		printf("\n");
	}
	printf("\n");

	B = (int**)malloc(sizeof(int*) * a);

	printf("Second matrix = \n");
	for (x = 0; x < a; x++)
	{
		B[x] = (int*)malloc(sizeof(int) * a);
	}

	for (x = 0; x < a; x++)
	{
		for (y = 0; y < a; y++)
		{
			B[x][y] = rand() % 10 + 1;
		}
	}

	for (x = 0; x < a; x++)
	{
		for (y = 0; y < a; y++)
		{
			printf("%3d", B[x][y]);
		}
		printf("\n");
	}
	printf("\n");

	C = (int**)malloc(sizeof(int*) * a);

	for (b = 0; b < a; b++)
	{
		C[b] = (int*)malloc(sizeof(int) * a);
	}

	printf("Result matrix = \n");
	for (b = 0; b < a; b++)
	{
		for (c = 0; c < a; c++)
		{
			sum = 0;
			for (d = 0; d < a; d++)
			{
				sum += A[b][d] * B[d][c];
				C[b][c] = sum;
			}
		}
	}
	for (b = 0; b < a; b++)
	{
		for (c = 0; c < a; c++)
		{
			printf("%4d", C[b][c]);
		}
		printf("\n");
	}
	printf("\n");

	for (i = 0; i < a; i++)
	{
		free(A[i]);
	}
	free(A);

	for (x = 0; x < a; x++)
	{
		free(B[x]);
	}
	free(B);

	for (b = 0; b < a; b++)
	{
		free(C[b]);
	}
	free(C);

	return 0;
}

homework_01_2019270774.docx
0.52MB