编写函数:分数的乘法 (Append Code)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <malloc.h>
struct fraction
{
    int numerator; // 分子
    int denominator; // 分母
    int symbol; // 符号,分子为负时取值为-1,为正时取值为1,其它取值无意义
};
int scan_frac(struct fraction *f, struct fraction *g)
{
      char ch;
      int temp1=0,temp2=0;
      f->symbol=1;f->numerator=0;f->denominator=0;
      while((ch=getchar())!='*')
      {
          if(isdigit(ch))
            temp1=temp1*10+ch-'0';
            else if(ch=='/')
            {f->numerator=temp1;temp1=0;}
            else if(ch=='-')
                f->symbol=-1;
      }
       f->denominator=temp1;
      g->symbol=1;g->numerator=0;g->denominator=0;
      while((ch=getchar())!='\n')
      {
             if(isdigit(ch))
              temp2=temp2*10+ch-'0';
            else if(ch=='/')
            {
                g->numerator=temp2;temp2=0;
            }
            else if(ch=='-')
                g->symbol=-1;
      }
      g->denominator=temp2;
}
struct fraction multiply_frac(struct fraction f, struct fraction g)
{
    struct fraction result;
    int a=0,b=0;
    a=f.numerator*g.numerator;
    b=f.denominator*g.denominator;
    int min=0;
    min=a<b?a:b;
    while(min>=2)
    {
        if(a%min==0&&b%min==0)
         {a/=min;b/=min;}  min--;
    }
        result.numerator=a;
        result.denominator=b;
        result.symbol=f.symbol*g.symbol;
     return result;
};
int main()
{
    struct fraction f1, f2, product;
    while(scan_frac(&f1, &f2) != EOF)
    {
        product = multiply_frac(f1, f2);
        if(product.numerator == 0)
        {
            printf("0\n");
            continue;
        }
        if(product.symbol == -1)
            printf("-");
        printf("%d/%d\n", product.numerator, product.denominator);
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值