匯東網


NOJ - T016

[編輯] [转简体]
|
作者:huidong | 分類:【編程】NOJ 和 C 程序設計習題
[ 2 瀏覽 0 評論 0 贊 0 踩 ]

概要
浮點數轉最簡分數

正文

#include <stdio.h>
#include <math.h>

int gcd(int m, int n)
{
    // 準備輾轉相除,首先使 a >= b,r 記錄餘數
    int a = m, b = n, r = 0;
    if (a < b)
        a ^= b ^= a ^= b;
    do
    {
        r = a % b;
        a = b;
        b = r;
    } while (r != 0);

    return a;
}

void ToFraction(double f, int& nu, int& de)
{
    de = 1;
    while (fabs(f - (int)f) >= 1e-6)
    {
        f *= 10;
        de *= 10;
    }
    nu = (int)f;
}

void SimplifyFraction(int& nu, int& de)
{
    int G = gcd(nu, de);
    if (G == 1)
        return;
    nu /= G;
    de /= G;
}

int main()
{
    double f;    // 浮點數
    int nu, de;    // 分子分母

    scanf("%lf", &f);

    // 轉基礎分式
    ToFraction(f, nu, de);

    // 化簡分式
    SimplifyFraction(nu, de);

    printf("%d/%d", nu, de);
    return 0;
}


[ 0] [ 0]


 評論區  0 條評論

+ 添加評論