main.c
1 #include "ch_1.h" 2 3 int main() 4 { 5 Triplet p; 6 Status i; 7 ElemType m; 8 i = InitList(&p,1,2,3); 9 printf("InitList: %d,%d,%d\n", p[0],p[1],p[2]); 10 11 i = Get(p, 2, &m); 12 if (i == OK) 13 printf("%d\n", m); 14 15 Put(p, 2, 3); 16 if (i == OK) 17 printf("%d,%d,%d\n", p[0], p[1], p[2]); 18 19 i = IsAscending(p); 20 printf("yes:1 no: 0 %d\n", i); 21 22 i = IsDesending(p); 23 printf("yes:1 no: 0 %d\n", i); 24 25 printf("max: %d\n", Max(p, &m)); 26 27 DestroyTriplet(&p); 28 return 0; 29 }
ch_1.h
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define OK 1 4 #define ERROR 0 5 #define OVERFLOW -2 6 typedef int ElemType; 7 typedef int Status; 8 typedef ElemType *Triplet; 9 10 Status InitList(Triplet *T, ElemType v1, ElemType v2, ElemType v3) //构造三元数组 11 { 12 *T = (ElemType*)malloc(3 * sizeof(ElemType)); 13 if (!*T) 14 exit(OVERFLOW); 15 (*T)[0] = v1; 16 (*T)[1] = v2; 17 (*T)[2] = v3; 18 return OK; 19 } 20 21 Status Get(Triplet T, int i, ElemType *e) //用e返回相应的元素值 22 { 23 if (i < 1 || i > 3) 24 return ERROR; 25 *e = T[i - 1]; 26 return OK; 27 } 28 29 Status Put(Triplet T, int i, ElemType e) //改变相应的元素值 30 { 31 if (i < 1 || i > 3) 32 return ERROR; 33 T[i - 1] = e; 34 } 35 36 Status IsAscending(Triplet T) //升序 37 { 38 return((T[0] <= T[1]) && (T[1] <= T[2])); 39 } 40 41 Status IsDesending(Triplet T) //降序 42 { 43 return((T[0] >= T[1]) && (T[1] >= T[2])); 44 } 45 46 Status Max(Triplet T, ElemType *e) 47 { 48 if (T[0] >= T[1]) 49 { 50 if (T[0] >= T[2]) 51 *e = T[0]; 52 else 53 *e = T[2]; 54 } 55 56 else 57 { 58 if (T[1] >= T[2]) 59 *e = T[1]; 60 else 61 *e = T[2]; 62 } 63 } 64 65 Status DestroyTriplet(Triplet *T) 66 { 67 free(*T); 68 *T = NULL; 69 return OK; 70 }
运行结果:
InitList: 1,2,3
2
1,3,3
yes:1 no: 0 1
yes:1 no: 0 0
max: 3
时间: 2024-10-14 10:24:30