分数四则运算

预备知识:
1、分数化简

第一种情况:如假分数17/2,最终需要化简成8 1/2;即a b/c的形式
其中a = 分子/分母; b = 分子%分母;c是分母
第二种情况:6/9,需要化简成2/3;即将分子分母同时除以最大公约数
求最大公约数算法如下:

/*a 和 b的最大公约数*/
int gcd(int a, int b){
	if(b == 0) return a;
	else return gcd(b, a % b);

一、加减法运算

/*
1、分数相加
2、约分
3、判断是否是假分数,化简
*/
#include
#include
void print(int up, int down) {
	if (up > down) {
		if (up % down == 0)
			printf("%d\n", up / down);
		else
			printf("%d %d/%d\n", up / down, up % down, down);
	}
	else if (up < down && up != 0)
		printf("%d/%d\n", up, down);
	else if (up < down && up == 0)
		printf("0\n");
	else
		printf("1\n");
}
/*求a,b的最大公约数*/
int gcd(int a, int b) {
	if (b == 0) return a;
	else return gcd(b, a % b);
}
/*加法*/
void addRationalNumber(int up1, int down1, int up2, int down2, int *up, int *down) {
	int temp;
	*down = down1 * down2;
	if ((up1 * down2 + up2 * down1) >= 0)  //+
		*up = up1 * down2 + up2 * down1;
	else {                         //-
		printf("-");
		*up = -1 * (up2 * down1 + up1 * down2);  //up一定是正数
	}
	temp = gcd(*up, *down);
	*down /= temp;
	*up /= temp;
}
/*减法*/
void subRationalNumber(int up1, int down1, int up2, int down2, int *up, int *down) {
	int temp;
	*down = down1 * down2;
	if(up1 * down2 >= up2 * down1)  //+
		*up = up1 * down2 - up2 * down1;
	else {                         //-
		printf("-");
		*up = up2 * down1 - up1 * down2;  //up一定是正数
	}    
	temp = gcd(*up, *down);
	*down /= temp;
	*up /= temp;
}
int main(void) {
	int up1, down1, up2, down2;
	int up, down;
	scanf("%d/%d %d/%d", &up1, &down1, &up2, &down2);
	/*分母大于0*/
	if (down1 <= 0 || down2 <= 0)
		return 0;
	/*加法*/
	addRationalNumber(up1, down1, up2, down2, &up, &down);
	print(up, down);
	/*减法*/
	subRationalNumber(up1, down1, up2, down2, &up, &down);
	print(up, down);
	return 0;
}

你可能感兴趣的:(算法系列)