分数的乘法

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

 

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 962  Solved: 278
[Submit][Status][Web Board]

Description

设有两个分数a/b和c/d,计算这两个分数的乘积,输出该乘积的最简分数形式。

 

分数乘法的运算方法:分数的分子与分子相乘,分母与分母相乘。

 

分子、分母只有公因数1的分数,或者说分子和分母互质的分数,叫做最简分数,又称既约分数。

 

-----------------------------------------------------------------------------

 

编写以下两个个函数完成程序:

 

原型:int scan_frac(struct fraction *f, struct fraction *g);

 

功能:按题目格式输入两个分数,存入f和g所指的内存中。

 

原型:struct fraction multiply_frac(struct fraction f, struct fraction g);

 

功能:返回分数f和g的乘积。

 

-----------------------------------------------------------------------------

 

“Append Code”中用到如下结构体定义:

 

struct fraction
{
    int numerator; // 分子
    int denominator; // 分母
    int symbol; // 符号,分子为负时取值为-1,为正时取值为1,其它取值无意义
};
 

Input

输入为多行,直到EOF结束。每行为一组测试数据,形如“a/b*c/d”。

 

a/b为一个分数,a为分子,b为分母;其中,b为正整数,a为任意整数,a为负数时表示整个分数是负数,a为0时则整个分数为0。

 

c/d格式同a/b。

 

Output

输出为多行,每行对应一个输入,为a/b和c/d的乘积,并且是该乘积的最简分数形式。

 

如果乘积为0,则输出只有一种形式:0。

 

Sample Input

1/3*2/320/15*150/800/77*9/16/6*4/412/16*4/333/48*6/11

Sample Output

2/95/201/11/13/8
 
#include <stdio.h>
#include <stdlib.h>
struct fraction
{
    int numerator; // 分子
    int denominator; // 分母
    int symbol; // 符号,分子为负时取值为-1,为正时取值为1,其它取值无意义
};
int gcd(int a, int b)
{
    if(a==0)
        return b;
    if(b==0)
        return a;
    int t;
    if (a>b)
    {
        t = b;
        b = a;
        a = t;
    }
    while (b%a != 0)
    {
        t = b%a;
        b = a;
        a = t;
    }
    return a;
}
int scan_frac(struct fraction *f, struct fraction *g)
{
    return scanf("%d/%d*%d/%d", &f->numerator, &f->denominator, &g->numerator, &g->denominator);
}


struct fraction multiply_frac(struct fraction f, struct fraction g)
{
    int m = f.numerator*g.numerator;
    int n = f.denominator*g.denominator;
    struct fraction k;
    k.numerator = abs(m) / gcd(abs(m), n);
    k.denominator = n / gcd(abs(m), n);
    k.symbol = m > 0 ? 1 : -1;
    return k;
}
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;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值