相关知识
A的转置矩阵B满足B(i,j)=A(j,i)
编程要求
先把你已经通过的第一关的SM_SetAt代码复制过来,然后编写本关的代码
SparseMatrix* SM_Trans(SparseMatrix *A)。
在这个代码里,你需要自己创建一个稀疏矩阵A的转置矩阵,并返回。,
测试说明
平台会对你编写的代码进行测试:
测试输入:1 2 0.3;
预期输出:"correct!\n"
开始
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "SparseMatrix.h"
SparseMatrix* SM_Create(int rows, int cols, int maxnodes)
// 创建一个稀疏矩阵。
{
SparseMatrix* A=(SparseMatrix*)malloc(sizeof(SparseMatrix));
A->nodes=SL_Create(maxnodes); //给三元组表分配内存
A->Rows=rows;
A->Cols=cols;
A->maxnodes=maxnodes;
return A;
}
void SM_Free(SparseMatrix* A)
// 释放/删除 稀疏矩阵。
{
SL_Free(A->nodes);
free(A);
}
int SM_Length(SparseMatrix* A)
// 获取长度。
{
return SL_Length(A->nodes);
}
//设计这个小函数很好用,给读和写矩阵元素带来方便
int SM_Loc(SparseMatrix* A, int row, int col ){
if(row<0||row>=A->Rows||col<0||col>=A->Cols) {
return -2; // -2表示坐标非法
}
else {
for (int k=0;k<SL_Length(A->nodes);k++){
T x=SL_GetAt(A->nodes, k); //在nodes表中取元素
if(x.row ==row && x.col==col)
return k ; //查到了
}
return -1; // 没查到三元组元素
}
}
TV SM_GetAt(SparseMatrix* A, int row, int col)
// 获取稀疏矩阵的第row,col位置的数据。
{
int loc= SM_Loc(A,row,col);
if (loc==-2) {
printf("SM_GetAt(): location error when reading elements of the matrix!\n");
SM_Free(A);
exit(0);
}
else if (loc==-1)
return 0;
else {
return SL_GetAt(A->nodes, loc).value;
}
}
void SM_SetAt(SparseMatrix* A, int row, int col, TV x)
// 设置稀疏矩阵的第row,col位置的数据。
{
//begin 上一关通过的复制过来
A->nodes->data->row=row;
A->nodes->data->col=col;
A->nodes->data->value=x;
A->nodes->len++;
//end
}
SparseMatrix* SM_Trans(SparseMatrix *A){
//begin 求转置矩阵
int row,col;
double x;
row=A->nodes->data->col;
col=A->nodes->data->row;
x=A->nodes->data->value;
A->nodes->data->row=row;
A->nodes->data->col=col;
SM_SetAt(A,row,col,x);
A->nodes->len--;
T a=SL_GetAt(A->nodes,0);
// printf("%d %d %0.1lf",a.row,a.col,a.value);
// printf("%d %d %lf",A->nodes->data->row, A->nodes->data->col,A->nodes->data->value);
return A;
//end
}
void SM_Print(SparseMatrix* A)
// 打印整个顺序表。
{
if (SL_Length(A->nodes)==0) {
printf("The slist is empty.\n");
return;
}
for (int i=0; i<SL_Length(A->nodes); i++) {
T x=SL_GetAt(A->nodes, i);
printf("%d %d %lf\n", x.row, x.col, x.value);
}
}
bool SM_Equal(SparseMatrix* A, SparseMatrix* B){
if (A->Rows!=B->Rows && A->Cols != B->Cols)
return false;
if (SL_Length(A->nodes) != SL_Length(B->nodes))
return false;
for (int i=0;i<SL_Length(A->nodes);i++){
T a=SL_GetAt(A->nodes,i);
TV b=SM_GetAt(B,a.row,a.col);
//printf("%f %f",a.value,b);
if (fabs(b-a.value)>SMALL) return false;
}
return true;
}
你的任务吧,祝你成功!
因篇幅问题不能全部显示,请点此查看更多更全内容