實驗報告:抽象數據類型的表現和實現
實驗內容
基本要求:
設計實現抽象數據類型“三元組”,要求動態分配內存。每個三元組由任意三個實數的序列構成,基本操作包括:創建一個三元組,取三元組的任意一個分量,置三元組的任意一個分量,求三元組的最大分量,求三元組的最小分量,顯示三元組,銷毀三元組等。
/* Auther: XDate:2020/2/15Description: 數據結構與算法*實驗一*抽象數據結構 */
#include<stdio.h>
#define OK 1
#define ERROR 0
typedef int status;typedef float Elemtype;
typedef int Status;typedef struct
{Elemtype e[3];}Triplet;//初始化三元組;
Status InitTriplet(Triplet &T,Elemtype v0,Elemtype v1,Elemtype v2)
{T.e[0]=v0;T.e[1]=v1;T.e[2]=v2;return OK;
}// 取三元組中第i個值賦值給e
Status Put(Triplet T,Status i,Elemtype &e)
{if(i<1||i>3)return ERROR;elsee=T.e[i-1];return OK;}//取三元組中最大值賦值給e
Status Getmax(Triplet &T,Status i,Elemtype &e)
{e=T.e[0];for(i=0;i<3;i++)if(T.e[i]>e)e=T.e[i];return OK;
}//取三元組中最小值賦值給e
Status Getmin(Triplet &T,Status i,Elemtype &e)
{e=T.e[0];for(i=0;i<3;i++)if(T.e[i]<e)e=T.e[i];return OK;
}//輸出三元組的三個值;
Status ShowTriplet(Triplet &T,Status i)
{if(i<1||i>3)return ERROR;elseprintf("三元組的3個值為:");for(i=0;i<3;i++)printf("%2f",T.e[i]);return OK; } //判斷三元組中的值是否為升序;
Status IsAscending(Triplet &T)
{return((T.e[0]<T.e[1])&&(T.e[1]<T.e[2]));//升序則返回1,否則返回0;
}//判斷三元組中的值是否為降序;;
Status IsDescending(Triplet &T)
{return((T.e[0]>T.e[1])&&(T.e[1]>T.e[2]));//降序則返回1,否則返回0; } //輸出三元組中數值的乘積;
Status GetProduct(Triplet &T,Status i,Elemtype &e)
{e=T.e[0]*T.e[1]*T.e[2];return OK;} //銷毀三元組;
Status Destory(Triplet &T)
{return OK;} int main()
{Triplet T;Status i,flag;Elemtype v0,v1,v2,e;printf("輸入三元組的值:\n");scanf("%f %f %f",&v0,&v1,&v2);flag=InitTriplet(T,v0,v1,v2);printf("初始化函數后,flag=%d\n,",flag);printf("三元組中三個值分別為:%4.2f,%4.2f,%4.2f\n",T.e[0],T.e[1],T.e[2]);Put(T,i,e);printf("取三元組中第i個值賦值給e:%d\n ",e);Getmax(T,i,e);printf("輸出三元組中的最大值:%f\n",e);Getmin(T,i,e);printf("輸出三元組中的最小值:%f\n",e);if (IsAscending(T))printf("三元組是升序") ;if(IsDescending(T)) printf("三元組是降序");GetProduct(T,i,e);printf("輸出三元組三個元素值的成績:%f%f%f\n",T.e[0],T.e[1],T.e[2]);flag=Destory(T);printf("銷毀三元組T成功:flag=%d\n",flag);return OK;}
三元組相比上學期的指針在功能上更加豐富,且更易理解。
同時更加從系統角度出發,例如typedef int Status;可以是系統更容易修改數值的數據類型