分数求和
时间: 1ms 内存:128M
描述:
求两分数相加,输出结果。
输入:
题目有多组测试数据,直到文件尾。
每组测试数据需要输入4个整数:
nume1, deno1为第一个数的分子和分母,nume2, deno2为第二个数的分子和分母。
输出:
两分数相加的结果。每个测试数据占一行。
输出格式为“nume3/deno3”,该格式对结果为整数的情况除外。
分母为0的情况不考虑。
示例输入:
1 3 1 2
3 25 4 15
1 4 3 4
1 4 1 4
示例输出:
5/6
29/75
1
1/2
提示:
参考答案(内存最优[748]):
#include<stdio.h>
void output(int s1,int s2)
{
int i;
if(s1%s2==0)
printf("%d\n",s1/s2);
else
{
for(i=2;i<100;)
{
if(s1%i==0&&s2%i==0)
{
s1/=i;
s2/=i;
}
else
i++;
}
printf("%d/%d\n",s1,s2);
}
}
int main()
{
int a,b,c,d,s1,s2;
while(scanf("%d",&a)!=EOF)
{
scanf("%d%d%d",&b,&c,&d);
s2=b*d;
s1=a*d+b*c;
output(s1,s2);
}
return 0;
}
参考答案(时间最优[0]):
#include <stdio.h>
int gcd(int m,int n)
{
if(m==0 || n==0)
return 1;
if(m<n){
int t;
t=m;m=n;n=t;
}
while(m%n){
int t = m%n;
m=n;n=t;
}
return n;
}
int main()
{
int z1,m1,z2,m2;
while(scanf("%d%d%d%d",&z1,&m1,&z2,&m2)!=EOF){
int lcm = m1*m2/gcd(m1,m2);
z1 = lcm/m1*z1;
z2 = lcm/m2*z2;
int z3 = z1 + z2;
int m3 = lcm;
int t=gcd(z3,m3);
z3/=t;m3/=t; //约分
if(z3%m3==0) //分子能整除分母或者分子为0的时候
printf("%d\n",z3/m3);
else{
printf("%d/%d\n",z3,m3);
}
}
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。
