C011:分数相加

代码:

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int up1,down1,up2,down2;

    do{
        printf("Enter two fractions seperated by a plus sign:");
        scanf("%d/%d+%d/%d",&up1,&down1,&up2,&down2);
        int down3=down1*down2;
        int up3=up1*down2+up2*down1;

        int small=(up3<down3)?up3:down3;
        int gcd;
        for(;small>1;small--){
            if(up3%small==0 && down3%small==0)
            {
                gcd=small;
                break;
            }
        }
        
        printf("The sum is %d/%d\n",up3/gcd,down3/gcd);
    }while(up1!=999);

    return 0;
}

代码:

Enter two fractions seperated by a plus sign:1/2+1/2
The sum is 1/1
Enter two fractions seperated by a plus sign:3/12+2/12
The sum is 5/12
Enter two fractions seperated by a plus sign:1/6+2/6
The sum is 1/2
Enter two fractions seperated by a plus sign:1/2+3/6
The sum is 1/1
Enter two fractions seperated by a plus sign:5/6+3/4
The sum is 19/12

--2020年6月9日--

posted @ 2020-06-09 20:36  逆火狂飙  阅读(286)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东