1088 Rational Arithmetic (20point(s)) - C語言 PAT 甲級

1088 Rational Arithmetic (20point(s))

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.

Input Specification:

Each input file contains one test case, which gives in one line the two rational numbers in the format a1/b1 a2/b2. The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.

Output Specification:

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is number1 operator number2 = result. Notice that all the rational numbers must be in their simplest form k a/b, where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output Inf as the result. It is guaranteed that all the output integers are in the range of long int.

Sample Input:

2/3 -4/2

Sample Output:

2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)

Sample Input:

5/3 0/6

Sample Output:

1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf

題目大意:

1034 有理數四則運算 (20point(s))

設計思路:

1034 有理數四則運算(C語言)

  1. 先約分,後輸出
  2. 約分過程需要找最大公約數
編譯器:C (gcc)
#include <stdio.h>

void printrational(long a, long b);
long MaxCommonDivisor(long a, long b);

int main()
{
    long a1, b1, a2, b2;
    char ch[4] = {'+', '-', '*', '/'};
    int i;

    scanf("%ld/%ld %ld/%ld", &a1, &b1, &a2, &b2);
    for(i = 0; i < 4; i++){
        printrational(a1, b1);
        printf(" %c ", ch[i]);
        printrational(a2, b2);
        printf(" = ");
        switch(ch[i]){
            case '+': printrational(a1 * b2 + a2 * b1, b1 * b2); break;
            case '-': printrational(a1 * b2 - a2 * b1, b1 * b2); break;
            case '*': printrational(a1 * a2, b1 * b2); break;
            case '/': printrational(a1 * b2, b1 * a2); break;
        }
        printf("\n");
    }
    return 0;
}

void printrational(long a, long b)
{
    int sign = 1;
    long mcd = 1;
    if(b == 0){
        printf("Inf");
        return;
    }
    if(a < 0){
        a = -a;
        sign *= -1;
    }
    if(b < 0){
        b = -b;
        sign *= -1;
    }
    mcd = MaxCommonDivisor(a, b);
    a /= mcd; b /= mcd;

    if(sign < 0) printf("(-");
    if(a / b && a % b){
        printf("%ld %ld/%ld", a / b, a % b, b);
    }
    else if(a % b){
        printf("%ld/%ld", a, b);
    }
    else{
        printf("%ld", a / b);
    }
    if(sign < 0) printf(")");
}

long MaxCommonDivisor(long a, long b)
{
    long x;
    while((x = a % b)){
        a = b;
        b = x;
    }
    return b;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章