c语言——分数加减

题目描述:

小明最害怕分数的减法运算,因为对输出结果有特别的要求。首先是要对分数化简,然后是假分数要写成一个整数+真分数的形式,更麻烦的是,当结果是负的假分数时,要求写成一个负整数+正的真分数的形式。你能帮帮他吗?

输入:多组样例。每行一个样例以a/b-c/d或a/b+c/d的形式输入(a,b,c,d都是小于10000的正整数)。

输出:对于每一个输入的样例,输出一个结果。注意对结果要化简。如果是整数就直接输出,不需要以分数形式输出,如果是真分数就直接以e/f的形式输出,如果假分数如5/3,则以1+2/3的形式输出,如果是-5/3,则以-2+1/3的形式输出。

样例输入:

1/1-2/3
1/2+2/3
1/2-8/2

样例输出:

1/3
1+1/6
-4+1/2

——————————————————————————————————————

看样例,要进行加减两种算法,那么要先判断输入的是加还是减,这个可以用一个char进行记录。

int a,b,c,d;
char ch;
scanf("%d/%d%c%d/%d",&a,&b,&ch,&c,&d);
if(ch=='+')
{}
else
{}

然后分别进行加减的运算。

但我们先看加减都要用到的公共部分。

无论是加还是减都要对分母进行约分,我们来写一个运用辗转相除法获得最大公约数的函数:

int get_maxInShu(int a,int b)
{
    if(a

加法很简单,因为一定是个正数,无需什么特别的操作。

int pre_son=a*d+c*b;
int pre_mon=b*d;
int maxInShu = get_maxInShu(pre_son,pre_mon);
pre_son/=maxInShu;
pre_mon/=maxInShu;
if(pre_son%pre_mon==0)
  printf("%d\n",pre_son/pre_mon);
else if(pre_son>pre_mon)
{
printf("%d+%d/%d\n",pre_son/pre_mon,per_son%per_mon,pre_mon);
}
else
{
printf("%d/%d\n",per_son,per_mon);
}

相减的话只是在算出分子后判断是正还是负数,

正数就与上面一样处理,负数就变成正,再在前头打印个负号,照题目操作一下就可以了;

if(pre_son<0)
{pre_son=0-per_son;

//这里的操作同上面

int maxInShu = get_maxInShu(pre_son,pre_mon);
pre_son/=maxInShu;
pre_mon/=maxInShu;

//只有打印这里要改一下

if(pre_son%pre_mon==0)
  printf("-%d\n",pre_son/pre_mon);
else if(pre_son

再把所有东西组合起来就可以了。

总代码:

#include 
int get_maxInShu(int,int);
int main()
{
    int a,b,c,d,pre_son,pre_mon,maxInShu;
    char ch;
    while(scanf("%d/%d%c%d/%d",&a,&b,&ch,&c,&d)!=EOF)
    {


    if(ch=='+')
    {pre_son=a*d+c*b;}
    else
    {pre_son=a*d-c*b;}
    if(pre_son==0)
    {
        printf("0\n");
        continue;
    }
     pre_mon=b*d;
    if(pre_son>0)
    {
        maxInShu = get_maxInShu(pre_son,pre_mon);
        pre_son/=maxInShu;
        pre_mon/=maxInShu;
        if(pre_son%pre_mon==0)
        printf("%d\n",pre_son/pre_mon);
        else if(pre_son>pre_mon)
        printf("%d+%d/%d\n",pre_son/pre_mon,pre_son%pre_mon,pre_mon);
        else
        printf("%d/%d\n",pre_son,pre_mon);
    }
    else
    {
        pre_son=0-pre_son;

    //这里的操作同上面

    maxInShu = get_maxInShu(pre_son,pre_mon);
    pre_son/=maxInShu;
    pre_mon/=maxInShu;

    //只有打印这里要改一下

    if(pre_son%pre_mon==0)
    printf("-%d\n",pre_son/pre_mon);
    else if(pre_son

你可能感兴趣的:(c语言)