本题要求编写程序,计算2个有理数的和、差、积、商。
输入格式:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为0。
输出格式:
分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中没有超过整型范围的整数。
输入样例1:
2/3 -4/2
输出样例1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例2:
5/3 0/6
输出样例2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf
错误代码:
/*************************************************************************> File Name: 1034.c> Author: YueBo > Function: 有理数的四则运算> Created Time: 2016年11月18日 星期五 12时55分10秒************************************************************************/#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct rNum1 {long long a, b;
};void print(struct rNum1* pr)
{long long m, m1, n, q, i;n = abs(pr->b);if (n == 0) { //如果分母为0,啥都不用说了printf("Inf");return;}m = abs(pr->a) % abs(pr->b);q = pr->a / pr->b;if (m != 0) { //化简真分数for (i = 2; i <= m; i++) {if (m%i==0 && n%i==0) {m = m / i;n = n / i;i = 1; //刚开始i=2老是出错}}}if (pr->a >= 0) {if (m == 0) { //如果分子为0printf("%lld", q);} else if (q != 0) {printf("%lld %lld/%lld", q, m, n);} else {printf("%lld/%lld", m, n);}} else {if (m == 0) {printf("(%lld)", q);}else if (q != 0) {printf("(%lld %lld/%lld)", q, m, n);} else {printf("(-%lld/%lld)", m, n);}}
}void plus(struct rNum1* pr1, struct rNum1* pr2, struct rNum1* pr3)
{pr3->b = pr1->b * pr2->b;pr3->a = pr1->a * pr2->b + pr2->a * pr1->b;
}void minus(struct rNum1* pr1, struct rNum1* pr2, struct rNum1* pr3)
{pr3->b = pr1->b * pr2->b;pr3->a = pr1->a * pr2->b - pr2->a * pr1->b;
}void times(struct rNum1* pr1, struct rNum1* pr2, struct rNum1* pr3)
{pr3->b = pr1->b * pr2->b;pr3->a = pr1->a * pr2->a;
}void division(struct rNum1* pr1, struct rNum1* pr2, struct rNum1* pr3)
{if (pr2->a > 0) {pr3->b = pr1->b * pr2->a;pr3->a = pr1->a * pr2->b;} else {pr3->b = (-1)*pr1->b * pr2->a;pr3->a = (-1)*pr1->a * pr2->b;}
}int main()
{struct rNum1 r1, r2, r3;scanf("%lld/%lld", &r1.a, &r1.b);scanf("%lld/%lld", &r2.a, &r2.b);//加法plus(&r1, &r2, &r3);print(&r1);printf(" + ");print(&r2);printf(" = ");print(&r3);printf("\n");//减法minus(&r1, &r2, &r3);print(&r1);printf(" - ");print(&r2);printf(" = ");print(&r3);printf("\n");//乘法times(&r1, &r2, &r3);print(&r1);printf(" * ");print(&r2);printf(" = ");print(&r3);printf("\n");//除法division(&r1, &r2, &r3);print(&r1);printf(" / ");print(&r2);printf(" = ");print(&r3);return 0;
}
提示错误: