在此示例中,您将学习将两个矩阵相乘并使用用户定义的函数进行显示。
要理解此示例,您应该了解以下C语言编程主题:
该程序要求用户输入矩阵的大小(行和列)。
然后,它要求用户输入这些矩阵的元素,最后添加并显示结果。
要执行此任务,需要执行三个函数:
要从用户那里获取矩阵元素 - enterData()
乘以两个矩阵 - multiplyMatrices()
在乘法后显示结果矩阵 - display()
#include <stdio.h>
void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond);
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int multResult[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond);
void display(int mult[][10], int rowFirst, int columnSecond);
int main()
{
int firstMatrix[10][10], secondMatrix[10][10], mult[10][10], rowFirst, columnFirst, rowSecond, columnSecond, i, j, k;
printf("输入第一个矩阵的行和列: ");
scanf("%d %d", &rowFirst, &columnFirst);
printf("输入第二个矩阵的行和列: ");
scanf("%d %d", &rowSecond, &columnSecond);
//如果第一矩阵的列不等于第二矩阵的行,则要求用户再次输入矩阵的大小。
while (columnFirst != rowSecond)
{
printf("错误! 第一矩阵的列不等于第二行。\n");
printf("输入第一个矩阵的行和列: ");
scanf("%d%d", &rowFirst, &columnFirst);
printf("输入第二矩阵的行和列: ");
scanf("%d%d", &rowSecond, &columnSecond);
}
//获取矩阵数据函数
enterData(firstMatrix, secondMatrix, rowFirst, columnFirst, rowSecond, columnSecond);
//用于将两个矩阵相乘的函数。
multiplyMatrices(firstMatrix, secondMatrix, mult, rowFirst, columnFirst, rowSecond, columnSecond);
//函数显示相乘后的合成矩阵
display(mult, rowFirst, columnSecond);
return 0;
}
void enterData(int firstMatrix[][10], int secondMatrix[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond)
{
int i, j;
printf("\n输入矩阵元素 1:\n");
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnFirst; ++j)
{
printf("输入元素 a%d%d: ", i + 1, j + 1);
scanf("%d", &firstMatrix[i][j]);
}
}
printf("\n输入矩阵元素 2:\n");
for(i = 0; i < rowSecond; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
printf("输入元素 b%d%d: ", i + 1, j + 1);
scanf("%d", &secondMatrix[i][j]);
}
}
}
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int mult[][10], int rowFirst, int columnFirst, int rowSecond, int columnSecond)
{
int i, j, k;
//将矩阵mult的元素初始化为0。
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
mult[i][j] = 0;
}
}
//将矩阵firstMatrix和secondMatrix相乘并存储在数组mult中。
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
for(k=0; k<columnFirst; ++k)
{
mult[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}
void display(int mult[][10], int rowFirst, int columnSecond)
{
int i, j;
printf("\n输出矩阵:\n");
for(i = 0; i < rowFirst; ++i)
{
for(j = 0; j < columnSecond; ++j)
{
printf("%d ", mult[i][j]);
if(j == columnSecond - 1)
printf("\n\n");
}
}
}
输出结果
输入第一个矩阵的行和列: 3
2
输入第二个矩阵的行和列: 3
2
错误!第一矩阵的列不等于第二矩阵的行。
输入第一个矩阵的行和列: 2
3
输入第二矩阵的行和列: 3
2
输入矩阵元素 1:
输入元素 a11: 3
输入元素 a12: -2
输入元素 a13: 5
输入元素 a21: 3
输入元素 a22: 0
输入元素 a23: 4
输入矩阵元素 2:
输入元素 b11: 2
输入元素 b12: 3
输入元素 b21: -9
输入元素 b22: 0
输入元素 b31: 0
输入元素 b32: 4
输出矩阵:
24 29
6 25