1 /* 2 * Main.c 3 * F2-结构-02. 有理数加法 4 * Created on: 2014年8月25日 5 ********测试通过********* 6 */ 7 8 #include <stdio.h> 9 /** 10 * 有理数结构体 11 */ 12 struct rationalNumber{ 13 int numerator; 14 int denominator; 15 }; 16 /** 17 * 最大公约数 18 */ 19 int greatCommonDivisor(int m,int n){ 20 int i; 21 for(i=(m<n?m:n);i>1;i--){ 22 if(m%i==0&&n%i==0) 23 break; 24 } 25 return i; 26 } 27 28 int main(void){ 29 30 struct rationalNumber num1,num2,num3; 31 scanf("%d/%d %d/%d",&num1.numerator,&num1.denominator,&num2.numerator,&num2.denominator); 32 33 //通分求和并赋值于num3 34 num3.numerator =num1.numerator*num2.denominator + num2.numerator*num1.denominator; 35 num3.denominator = num1.denominator*num2.denominator; 36 37 //约分 38 int gcd = greatCommonDivisor(num3.numerator,num3.denominator); 39 num3.numerator/=gcd; 40 num3.denominator/=gcd; 41 42 //输出结果 43 if(num3.denominator==1) 44 printf("%d\n",num3.numerator); 45 else 46 printf("%d/%d\n",num3.numerator,num3.denominator); 47 48 return 0; 49 }
题目链接:
http://pat.zju.edu.cn/contests/basic-programming/%E7%BB%93%E6%9E%84-02
参考引用:
http://blog.csdn.net/rabbit8848/article/details/30283935
.
时间: 2024-10-13 11:16:22