View Code of Problem 3494

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int gcd(int x,int y)
{
	if(y==0)
	{
		return x;
	}
	return gcd(y,x%y);
}
int main() {
	int a,b,c,d;
	char s;
	while(scanf("%d/%d%c%d/%d",&a,&b,&s,&c,&d)!=EOF)
	{
		int x,y;//x表示分子,y表示分母
		if(s=='+')
		{
			if(b==d)
			{
				x=a+c;
				y=b;
			}
			else
			{
				x=a*d+c*b;
				y=b*d;
			}
		}
		else
		{
			if(b==d)
			{
				x=a-c;
				y=b;
			}
			else
			{
				x=a*d-c*b;
				y=b*d;
			}
		}
		if(x==0)
		{
			printf("0\n");
		}
		else
		{
			int m=x/gcd(abs(x),y);
			int n=y/gcd(abs(x),y);
			if(n==1)
			{
				printf("%d\n",m);
			}
			else
			{
				printf("%d/%d\n",m,n);
			}
		}
	}

	return 0;
}

Double click to view unformatted code.


Back to problem 3494