介绍
给你两个分数,计算两者和及差。
分析
直接模拟两个分数相加的过程就可以了,注意要约分。
代码
#include<stdio.h>
#include<stdlib.h>
int Divisor(int m_a,int m_b)//求最大公约数
{
int a,divisor;
if(m_a>m_b)
{
a=m_a;
m_a=m_b;
m_b=a;
}
for(int i=1;i<=m_a;i++)
if(m_a%i==0&&m_b%i==0)
divisor=i;
return divisor;
}
int main()
{
int den_a,num_a,den_b,num_b;
int den_num,num_num;
int divisor;
printf("请输入第一个分数的分子和分母:\n");
scanf("%d %d",&num_a,&den_a);
printf("请输入第二个分数的分子和分母:\n");
scanf("%d %d",&num_b,&den_b);
den_num=den_a*den_b;
num_num=den_a*num_b+den_b*num_a;
if(num_num%den_num==0)
printf("%d/%d + %d/%d = %d\n",num_a,den_a,num_b,den_b,num_num/den_num);
else
{
divisor=Divisor(den_num,num_num);
den_num=den_num/divisor;
num_num=num_num/divisor;
printf("%d/%d + %d/%d = %d/%d\n",num_a,den_a,num_b,den_b,num_num,den_num);
}
num_num=den_a*num_b-den_b*num_a;
if(num_num%den_num==0)
printf("%d/%d - %d/%d = %d\n",num_a,den_a,num_b,den_b,num_num/den_num);
else
{
divisor=Divisor(den_num,num_num);
den_num=den_num/divisor;
num_num=num_num/divisor;
printf("%d/%d - %d/%d = %d/%d\n",num_a,den_a,num_b,den_b,num_num,den_num);
}
system("pause");
return 0;
}
#include<stdlib.h>
int Divisor(int m_a,int m_b)//求最大公约数
{
int a,divisor;
if(m_a>m_b)
{
a=m_a;
m_a=m_b;
m_b=a;
}
for(int i=1;i<=m_a;i++)
if(m_a%i==0&&m_b%i==0)
divisor=i;
return divisor;
}
int main()
{
int den_a,num_a,den_b,num_b;
int den_num,num_num;
int divisor;
printf("请输入第一个分数的分子和分母:\n");
scanf("%d %d",&num_a,&den_a);
printf("请输入第二个分数的分子和分母:\n");
scanf("%d %d",&num_b,&den_b);
den_num=den_a*den_b;
num_num=den_a*num_b+den_b*num_a;
if(num_num%den_num==0)
printf("%d/%d + %d/%d = %d\n",num_a,den_a,num_b,den_b,num_num/den_num);
else
{
divisor=Divisor(den_num,num_num);
den_num=den_num/divisor;
num_num=num_num/divisor;
printf("%d/%d + %d/%d = %d/%d\n",num_a,den_a,num_b,den_b,num_num,den_num);
}
num_num=den_a*num_b-den_b*num_a;
if(num_num%den_num==0)
printf("%d/%d - %d/%d = %d\n",num_a,den_a,num_b,den_b,num_num/den_num);
else
{
divisor=Divisor(den_num,num_num);
den_num=den_num/divisor;
num_num=num_num/divisor;
printf("%d/%d - %d/%d = %d/%d\n",num_a,den_a,num_b,den_b,num_num,den_num);
}
system("pause");
return 0;
}
遇到的问题
问题不大