C语言笔记:定义结构体完成分数四则运算

#include 

typedef struct{				//定义“分数”结构体,num代表分子,denom分母
	int num;
	int denom;
}fraction;

fraction makeRat(int num, int denom);			//创建一个分数,num代表分子,denom代表分母
void Display(fraction r);						//显示一个分数

fraction add(fraction first, fraction second);	//分数的加
fraction sub(fraction first, fraction second);	//分数的减
fraction mul(fraction first, fraction second);	//分数的乘
fraction div(fraction first, fraction second);	//分数的除

fraction neg(fraction rat);						//求一个分数的相反数
fraction inv(fraction rat);						//求一个分数的倒数

int gcd(int a, int b);					//求两个数a和b最高公因数
int main(){
	fraction a,b,c,d;
	a = makeRat(1,2);
	b = makeRat(11,23);
	c = makeRat(5,6);
	d = makeRat(5,26);
	
	fraction result = div(add(a,b),sub(c,d));	
	Display(result);
	return 0;
}

fraction makeRat(int num, int denom){
	fraction rat;
	int i = gcd(num, denom);
	rat.num = num / i;
	rat.denom = denom / i;
	return rat;
}

void Display(fraction r){
	printf("%d / %d\n", r.num, r.denom);
}

fraction add(fraction first, fraction second){
	int num, denom;
	num = first.num * second.denom + first.denom * second.num;
	denom = first.denom * second.denom;
	return makeRat(num, denom);
}

fraction neg(fraction rat){
	return makeRat(-rat.num, rat.denom);
}

fraction sub(fraction first, fraction second){
	return add(first, neg(second));
}

fraction mul(fraction first, fraction second){
	int num, denom;
	num = first.num * second.num;
    denom = first.denom * second.denom;
    return makeRat(num, denom);
}

fraction inv(fraction rat){
	return makeRat(rat.denom, rat.num);
}

fraction div(fraction first, fraction second){
	return mul(first, inv(second));
}

int gcd(int a, int b){
	while(b != 0){
		int tmp = a % b;
		a = b;
		b = tmp;
	}
	return a;
}