1
写一个程序,实现分数相加。用户以分子/分母的形式输入分数,程序打印相加后的结果。如:
输入:
5/6
3/4
输出:
The sum is 19/12
辗转相除法化简
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
// 定义SWAP宏函数,用来交换两个整数
#define SWAP(x, y) { \
int tmp = x; \
x = y; \
y = tmp; \
}
int main(void) {
int num1, denom1;
printf("Enter first fraction: ");
scanf("%d/%d", &num1, &denom1);
int num2, denom2;
printf("Enter second fraction: ");
scanf("%d/%d", &num2, &denom2);
int result_num = num1 * denom2 + num2 * denom1;
int result_denom = denom1 * denom2;
int result_gcd = gcd(result_num, result_denom);
printf("The sum is %d/%d\n", result_num / result_gcd, result_denom / result_gcd);
return 0;
}
// 用辗转相除法求最大公约数: gcd(a, b) = gcd(b, r)
int gcd(int a, int b) {
if (a < b) {
SWAP(a, b);
}
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
标签:02,积累,面试题,denom2,gcd,int,denom1,num,result
From: https://www.cnblogs.com/MyXjil/p/17083978.html