在此示例中,您將學(xué)習(xí)將兩個矩陣相乘并使用用戶定義的函數(shù)進行顯示。
要理解此示例,您應(yīng)該了解以下C語言編程主題:
該程序要求用戶輸入矩陣的大?。ㄐ泻土校?。
然后,它要求用戶輸入這些矩陣的元素,最后添加并顯示結(jié)果。
要執(zhí)行此任務(wù),需要執(zhí)行三個函數(shù):
要從用戶那里獲取矩陣元素 - enterData()
乘以兩個矩陣 - multiplyMatrices()
在乘法后顯示結(jié)果矩陣 - 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);
}
//獲取矩陣數(shù)據(jù)函數(shù)
enterData(firstMatrix, secondMatrix, rowFirst, columnFirst, rowSecond, columnSecond);
//用于將兩個矩陣相乘的函數(shù)。
multiplyMatrices(firstMatrix, secondMatrix, mult, rowFirst, columnFirst, rowSecond, columnSecond);
//函數(shù)顯示相乘后的合成矩陣
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相乘并存儲在數(shù)組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");
}
}
}輸出結(jié)果
輸入第一個矩陣的行和列: 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