1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 10
struct Term
{
int row;
int col;
int value;
};
struct sMatrix
{
int rows;
int cols;
int numOfTerms;
struct Term smArr[MAX_TERMS];
};
typedef struct sMatrix Matrix;
Matrix m;
extern void createMatrix(int r,int c,int *arr);
extern void printMatrix();
void createMatrix(int r,int c,int *arr)
{
int i, j, count;
m.rows = r;
m.cols = c;
count = 0;
for ( i = 0; i < r; i++ )
for ( j = 0; j < c; j++ )
if ( arr[i*c+j] != 0 ) {
m.smArr[count].row = i;
m.smArr[count].col = j;
m.smArr[count].value = arr[i*c+j];
count++;
}
m.numOfTerms = count;
}
void printMatrix()
{
int i;
printf("尺寸: %d X %d", m.rows, m.cols);
printf(" 項目數: %d\n", m.numOfTerms);
printf("列row\t欄col\t值value\n");
for ( i = 0; i < m.numOfTerms; i++)
{
printf(" %d\t%d",m.smArr[i].row,m.smArr[i].col);
printf("\t%d\n", m.smArr[i].value);
}
}
int main()
{
int sparse[6][9] = { 0, 7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 5, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 1, 0, 0, 0,
2, 0, 0, 0, 4, 0, 0, 0, 0,
0, 0, 8, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 9, 0, };
int *fp = &sparse[0][0];
createMatrix(6, 9, fp);
printMatrix();
system("PAUSE");
return 0;
}
|
評分: ★★★★▲
回覆刪除Good Job!
請練習將程式分成 .h及 .c 執行方式.