-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestVector.c
More file actions
97 lines (90 loc) · 1.88 KB
/
Copy pathtestVector.c
File metadata and controls
97 lines (90 loc) · 1.88 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ElemType double
#define ERROR -2
#define MISMATCH -3 //(维数)不匹配
#define UNORDERED -4 //不能用顺序法求解
#define STRANGE 5 //矩阵奇异
#define E 1.0e-2 //相对误差限
typedef struct
{
int dimension; //维数
ElemType *elem; //向量,一维数组
} Vector;
//输入&V,n;初始化n维向量V(用1~n):
void VectorInit(Vector *v, int n)
{
v->dimension = n;
v->elem = (ElemType *)malloc(sizeof(ElemType) * (n + 1));
return;
}
//复制向量
void VectorCopy(Vector V, Vector *x)
{
if (V.dimension != x->dimension)
exit(MISMATCH);
for (int i = 1; i <= V.dimension; ++i)
{
(x->elem)[i] = V.elem[i];
}
return;
}
//打印向量
void PrintVector(Vector V)
{
for (int i = 1; i <= V.dimension; ++i)
{
printf("%lf ", V.elem[i]);
}
printf("\n");
return;
}
//向量数乘,V=向量U*数k(要求V已经初始化),传入V的指针,改变V后,返回V的指针
Vector *Vector_Num(Vector U, double k, Vector *v)
{
if (U.dimension == v->dimension)
{
for (int i = 1; i <= U.dimension; ++i)
{
v->elem[i] = U.elem[i] * k;
}
}
else
{
exit(MISMATCH);
}
return v;
}
//向量内积
double DotProduct(Vector X, Vector Y)
{
if (X.dimension == Y.dimension)
{
double p = 0;
for (int i = 1; i <= X.dimension; ++i)
{
p += X.elem[i] * Y.elem[i];
}
return p;
}
else
{
exit(MISMATCH);
}
}
int main()
{
Vector a;
VectorInit(&a, 5);
a.elem[1] = 1;
a.elem[5] = 5;
PrintVector(a);
Vector b;
VectorInit(&b, 5);
Vector_Num(a, 2, &b);
PrintVector(b);
printf("dot product a,b: %lf", DotProduct(a, b));
printf("dot product b,a: %lf", DotProduct(b, a));
return 0;
}