我的PAT系列文章更新重心已移至Github,歡迎來看PAT題解的小伙伴請到Github Pages瀏覽最新內容。此處文章目前已更新至與Github Pages同步。歡迎star我的repo。
題目
本題要求編寫程序,計算 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
思路
這道題的注意點就是分數的約分和表示。
- 題目限定了輸入輸出都不超過整型范圍,那么當我們計算兩個分數的加減乘除時,分子分母就應該不超過長整形范圍:
- 極限情況就是兩者之和/之差的分子為
- 極限情況就是兩者之和/之差的分子為
- 輸出形式共有3種:
- 假分數,輸出整數部分和真分數部分;
- 真分數,只輸出真分數部分;
- 整數,只輸出整數部分。
- 在判斷輸出的正負號時,如果分子分母還沒有約分,那么小心使用兩者之積來判斷符號,因為已經溢出長整形范圍。
代碼
最新代碼@github,歡迎交流
#include <stdio.h>
/* Both parameters take positive value */
long calcgcd(long a, long b)
{
long r;
while((r = a % b))
{
a = b;
b = r;
}
return b;
}
/* print a fraction number, giving the numerator and dominator */
void printfrac(long n, long d)
{
if(d == 0) { printf("Inf"); return; }
/* record the sign and make them positive */
int inegative = 1;
if(n < 0) { n = -n; inegative *= -1; }
if(d < 0) { d = -d; inegative *= -1; }
/* reduce the fraction */
long gcd = calcgcd(n, d);
n /= gcd;
d /= gcd;
/* print */
if(inegative == -1) printf("(-");
if(n / d && n % d) printf("%ld %ld/%ld", n / d, n % d, d); /* mixed fractions */
else if(n % d) printf("%ld/%ld", n % d, d); /* proper fractions */
else printf("%ld", n / d); /* integers */
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;
}