人工方式下比较分数大小最常用的方法是:进行分数的通分后比较分子的大小。编程实现模拟该过程,其中计算分母a和b的最小公倍数的函数定义形式如下:
int LCM(int a, int b)
{
}
**输入格式要求:"%d/%d,%d/%d" 提示信息:"Input two fractions\n"
**输出格式要求:"%d/%d>%d/%d\n"或者 "%d/%d=%d/%d\n"或者 "%d/%d<%d/%d\n"
运行结果示例:
Input two fractions
4/5,6/7
4/5<6/7
#include <stdio.h>
int LCM(int a, int b)
{
int min_common_factor;
int temp;
// 计算 a 和 b 的公因数
for (temp = 1; temp < a; temp++)
for (temp < b; temp++)
if (temp * temp <= a * b)
break;
// 如果存在公因数,则将其加到 a 和 b 的乘积中
if (temp * temp > a * b)
for (temp = a; temp * temp <= b; temp++)
b = temp;
else if (temp * temp < a * b)
for (temp = b; temp * temp <= a; temp++)
a = temp;
// 返回最小公倍数
return min_common_factor;
}
int main()
{
char direction;
int a, b, d1, d2;
int min_common_factor;
printf("Input two fractions:\n");
scanf("%d/%d,%d/%d", &a, &b, &d1, &d2);
// 计算最小公倍数
min_common_factor = LCM(b, d2);
// 判断方向 (大于、等于、小于)
if (min_common_factor / b * a > min_common_factor / d2 * b)
direction = '>';
else if (min_common_factor / b * a < min_common_factor / d2 * b)
direction = '<';
else
direction = '=';
// 输出结果
printf("%d/%d%c%d/%d\n", a, b, direction, d1, d2);
return 0;
}