星海's Blog

老头初学编程
最大公约数与Fibnacci的递归和循环实现
折半算法

合理的有理数实现 代码

星海 posted @ 2010年10月21日 03:57 in C代码 , 1618 阅读

 

/*
 * ==========================================================================
 *
 *       Filename:  prac.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2010年10月20日 16时50分14秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 ==========================================================================
 */
#include <stdio.h>
#include <math.h>

int euclid(int a, int b)
{
    if (a % b == 0)
        return abs(b);
    else
        return euclid(b, a % b);
}

struct rational {
    int x,y
} ;

struct rational add_rational (struct rational z1,struct rational z2)
{
    struct rational z;
    z.x = z1.x + z2.x;
    z.y = z1.y + z2.y;
    return z;
}
struct rational sub_rational (struct rational z1,struct rational z2)
{
    struct rational z;
    z.x = z1.x - z2.x;
    z.y = z1.y - z2.y;
    return z;
}
struct rational mul_rational (struct rational z1, struct rational z2)
{
    struct rational z;
    z.x = z1.x * z2.x;
    z.y = z1.y * z2.y;
    return z;
}
struct rational div_rational (struct rational z1, struct rational z2)
{
    struct rational z;
    z.x = z1.x / z2.x ;
    z.y = z1.y / z2.y ;
    return z;
}

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

int print_rational (struct rational z)
{
    if (z.y < 0) {
        z.x = -z.x;
        z.y = -z.y;
    }
    if (z.y == 0)
        printf ("0 不能做除数\n");
    else if (z.x % z.y == 0) //如果能被整除,则变为最简分数
        printf ("%d\n", z.x/z.y);
    else
    {
        int gcd= euclid( z.x,z.y);
        z.x = z.x/gcd;
        z.y = z.y/gcd;
        printf ("%d/%d\n", z.x, z.y);
    }
    return 0;
}

int main(void)
{
    struct rational a = make_rational(1, 8); 
    struct rational b = make_rational(-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;
}
Avatar_small
Kflayca 说:
2010年11月14日 04:21

写的不错……不过应该叫合理的坐标实现吧


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter