任务描述
相关知识
编程要求
测试说明
任务描述
本关任务:编写稀疏矩阵的加法函数。
相关知识
矩阵加法A+B需要把A和B对应位置的元素相加。稀疏矩阵表示中,如果元素之和为0,则这个元素不进入稀疏矩阵之和。
编程要求
先把你已经通过的第一关的SM_SetAt代码复制过来,然后编写本关的代码
SparseMatrix* SM_Add(SparseMatrix A, SparseMatrixB)
在这个代码里,你需要自己创建一个稀疏矩阵C, 计算C=A+B,并返回。,
测试说明
平台会对你编写的代码进行测试:
平台会对你编写的代码进行测试:
测试输入: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_Add(SparseMatrix *A, SparseMatrix*B){
//begin
SparseMatrix* C=SM_Create(10, 10, 20);
T* newnode=C->nodes->data;
if((A->nodes->data->col!=B->nodes->data->col)||(A->nodes->data->row!=B->nodes->data->row))
{
SM_SetAt(C,A->nodes->data->row,A->nodes->data->col,A->nodes->data->value);
newnode++;
newnode->row=B->nodes->data->row;
newnode->col=B->nodes->data->col;
newnode->value=B->nodes->data->value;
C->nodes->len++;
}
else{
if(A->nodes->data->value+B->nodes->data->value!=0)
SM_SetAt(C,B->nodes->data->row,B->nodes->data->col,A->nodes->data->value+B->nodes->data->value);
}
return C;
//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;
}