文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>用c语言做分数的加减乘除

用c语言做分数的加减乘除

时间:2010-12-21  来源:newbie2011

来自http://learn.akae.cn/media/ch07s02.html的c练习题。  

1、题目

实现一个用分子分母的格式来表示有理数的结构体rational以及相关的函数,rational结构体之间可以做加减乘除运算,运算的结果仍然是rational。测试代码如下:

int main(void)
{
        struct rational a = make_rational(1, 8); /* a=1/8 */
        struct rational b = make_rational(-1, 8); /* b=-1/8 */
        print_rational(add_rational(a, b));
        print_rational(sub_rational(a, b));
        print_rational(mul_rational(a, b));
        print_rational(div_rational(a, b));

        return 0;
}

注意要约分为最简分数,例如1/8和-1/8相减的打印结果应该是1/4而不是2/8

2、代码

#include <stdio.h>
#include <math.h>
struct rational
{
    int numerator,denominator;
};

int get_numerator(struct rational a)
{
    return a.numerator;
}

int get_denominator(struct rational a)
{
    return a.denominator;
}

struct rational make_rational(int a,int b)
{
    struct rational z;
    z.numerator=a;
    z.denominator=b;
    return z;
}

int gcd(int a,int b)
{
    int Max=a,Min=b;
    if(a<b)
    {
        Max=b;
        Min=a;
    }
    if(!(Max%Min))
        return Min;
    else
        return gcd(Min,Max%Min);
}

struct rational regulation_rational(struct rational a)
{
    int g=1;
    if(!a.numerator)
        return a;
    if(a.denominator<0)
    {
        a.numerator=-a.numerator;
        a.denominator=-a.denominator;
    }
    g=gcd(abs(a.numerator),abs(a.denominator));
    a.numerator=a.numerator/g;
    a.denominator=a.denominator/g;
    return a;
}

struct rational add_rational(struct rational a,struct rational b)
{
    struct rational z;
    z.numerator=a.numerator*b.denominator+b.numerator*a.denominator;
    z.denominator=a.denominator*b.denominator;
    return regulation_rational(z);
}

struct rational sub_rational(struct rational a,struct rational b)
{
    b.numerator=-b.numerator;
    return regulation_rational(add_rational(a,b));
}

struct rational mul_rational(struct rational a,struct rational b)
{
    struct rational z;
    z.numerator=a.numerator*b.numerator;
    z.denominator=a.denominator*b.denominator;
    return regulation_rational(z);
}

struct rational div_rational(struct rational a,struct rational b)
{
    struct rational z;
    z.numerator=a.numerator*b.denominator;
    z.denominator=b.numerator*a.denominator;
    return regulation_rational(z);
}

//打印之前需要最简化分数
void print_rational(struct rational a)
{
    if((!a.numerator)||(a.denominator==1))
        printf("%d\n",a.numerator);
    else
        printf("%d/%d\n",a.numerator,a.denominator);
}

int main(void)
{
    struct rational a = make_rational(1, 8); /* a=1/8 */
    struct rational b = make_rational(-1, 8); /* b=-1/8 */
    print_rational(add_rational(a, b));
    print_rational(sub_rational(a, b));
    print_rational(mul_rational(a, b));
    print_rational(div_rational(a, b));

    return 0;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载