预备知识:
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<stdio.h> 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; *up = up1 * down2 + up2 * down1; temp = gcd(*up, *down); //temp保存最大公约数的值 /*约分*/ *down /= temp; *up /= temp; } /*化简成a b/c的形式*/ void fenshu(int up, int down) { int a, b; a = up / down; b = up % down; printf("%d %d/%d", a, b, down); } int main(void) { int up1, down1, up2, down2; int up, down; scanf("%d/%d %d/%d", &up1, &down1, &up2, &down2); addRationalNumber(up1, down1, up2, down2, &up, &down); if (up > down) fenshu(up, down); else if(up < down) printf("%d/%d\n", up, down); else printf("1"); return 0; }
文章来源: https://blog.csdn.net/qq_43417071/article/details/91491723