通过重载运算符实现加法运算
通过函数实现转置运算
#define _CRT_SECURE_NO_WARNINGS
#define SWAP(a,b){a=a+b;b=a-b;a=a-b;}
#include<stdio.h>
#include<stdlib.h>
typedef struct Matrix {
int first[3];
int second[3];
int third[3];
Matrix()
{
int i;
for (i = 0; i < 3; i++) {
first[i] = second[i] = third[i] = 0;
}
}
Matrix operator+(Matrix& other)
{
Matrix sum;
int i;
for (i = 0; i < 3; i++) {
sum.first[i] = first[i] + other.first[i];
sum.second[i] = second[i] + other.second[i];
sum.third[i] = third[i] + other.second[i];
}
return sum;
}
};
void input_data(Matrix& M)
{
printf("请输入第一行数据(用逗号隔开): ");
scanf("%d,%d,%d", &M.first[0], &M.first[1], &M.first[2]);
printf("请输入第二行数据(用逗号隔开): ");
scanf("%d,%d,%d", &M.second[0], &M.second[1], &M.second[2]);
printf("请输入第三行数据(用逗号隔开): ");
scanf("%d,%d,%d", &M.third[0], &M.third[1], &M.third[2]);
}
void output_data(Matrix& M)
{
int i;
printf("| ");
for (i = 0; i < 3; i++) {
printf("%2d ", M.first[i]);
}
printf("|\n");
printf("| ");
for (i = 0; i < 3; i++) {
printf("%2d ", M.second[i]);
}
printf("|\n");
printf("| ");
for (i = 0; i < 3; i++) {
printf("%2d ", M.third[i]);
}
printf("|\n");
}
void transposition(Matrix& M)
{
int temp;
SWAP(M.first[2], M.third[0]);
SWAP(M.first[1], M.second[0]);
SWAP(M.second[2], M.third[1]);
}
int main(void)
{
Matrix A, B, S;
printf("请输入矩阵A\n");
input_data(A);
printf("请输入矩阵B\n");
input_data(B);
S = A + B;
printf("输出A与B的和S\n");
output_data(S);
printf("输出转置后的矩阵S\n");
transposition(S);
output_data(S);
system("pause");
return 0;
}