PAT_B_1034 有理數四則運算

題目描述

本題要求編寫程序,計算 2 個有理數的和、差、積、商。
輸入格式:
輸入在一行中按照 a1/b1 a2/b2 的格式給出兩個分數形式的有理數,其中分子和分母全是整型範圍內的整數,負號只可能出如今分子前,分母不爲 0。
輸出格式:
分別在 4 行中按照 有理數1 運算符 有理數2 = 結果 的格式順序輸出 2 個有理數的和、差、積、商。注意輸出的每一個有理數必須是該有理數的最簡形式 k a/b,其中 k 是整數部分,a/b 是最簡分數部分;若爲負數,則須加括號;若除法分母爲 0,則輸出 Inf。題目保證正確的輸出中沒有超過整型範圍的整數。
輸入樣例 1:
2/3 -4/2
輸出樣例 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
輸入樣例 2:
5/3 0/6
輸出樣例 2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf

AC代碼

#include <stdio.h>

long calcgcd(long a, long b)
{
    long r;
    while((r = a % b))
    {
        a = b;
        b = r;
    }
    return b;
}

void printfrac(long n, long d)
{
    if(d == 0) { printf("Inf"); return; }

    int inegative = 1;
    if(n < 0) { n = -n; inegative *= -1; }
    if(d < 0) { d = -d; inegative *= -1; }

    long gcd = calcgcd(n, d);
    n /= gcd;
    d /= gcd;

    if(inegative == -1)  printf("(-");
    if(n / d && n % d)   printf("%ld %ld/%ld", n / d, n % d, d); 
    else if(n % d)       printf("%ld/%ld", n % d, d);            
    else                 printf("%ld", n / d);                   
    if(inegative == -1)  printf(")");
}

int main()
{
    long a1, b1, a2, b2;
    scanf("%ld/%ld %ld/%ld", &a1, &b1, &a2, &b2);

    char op[4] = {'+', '-', '*', '/'};
    for(int i = 0; i < 4; i++)
    {
        printfrac(a1, b1);        printf(" %c ", op[i]);
        printfrac(a2, b2);        printf(" = ");
        switch(op[i])
        {
            case '+': printfrac(a1 * b2 + a2 * b1, b1 * b2); break;
            case '-': printfrac(a1 * b2 - a2 * b1, b1 * b2); break;
            case '*': printfrac(a1 * a2,           b1 * b2); break;
            case '/': printfrac(a1 * b2,           b1 * a2); break;
        }
        printf("\n");
    }

    return 0;
}

RRRspa

相關文章
相關標籤/搜索