其他分享
首页 > 其他分享> > 分数的四则运算

分数的四则运算

作者:互联网

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
using namespace std;

//分数的四则运算
int Gcd(int m,int n)
{
	int temp;
	if(m<n)  /*比较大小,使得m中存储大数,n中存储小数*/
    {
        temp = m;
        m = n;
        n = temp;
    }
    int t;
	for(int i = m; i > 0 ; i--)
	{
		if(m % i == 0 && n % i == 0)
		{
			t = i;
			break;
		}
	}
	return t;
}



void  plus(int a,int b,int c,int d)
{
	int fenzi,fenmu;
	fenmu = b * d;
	fenzi = a * d + b * c;
	int g;
	g = Gcd(fenmu,fenzi);
	fenmu = fenmu / g;
	fenzi = fenzi / g;
	if(fenzi == fenmu)
		printf("%d/%d + %d/%d = 1",a,b,c,d);
	else if(fenzi == 0)
		printf("%d/%d + %d/%d = 0",a,b,c,d);
	else 
		printf("%d/%d + %d/%d = %d/%d",a,b,c,d,fenzi,fenmu);
}


void minus(int a,int b,int c,int d)
{
	int fenzi,fenmu;
	int g;
	fenmu = b * d;
	fenzi = a * d - b * c;
	if(fenzi >= 0)
	{
		g = Gcd(fenmu,fenzi);
		fenmu = fenmu / g;
		fenzi = fenzi / g;
	}else
	{
		fenzi = -fenzi;
		g = Gcd(fenmu,fenzi);
		fenmu = fenmu / g;
		fenzi = fenzi / g;
		fenzi = -fenzi;
	}
	if(fenzi == 0 )
	{
		printf("%d/%d - %d/%d = 0\n",a,b,c,d);
	}
	else if(fenzi < 0 && abs(fenzi)== fenmu)
		printf("%d/%d - %d/%d = -1",a,b,c,d);
	else if(fenzi > 0 && fenzi == fenmu)
		printf("%d/%d - %d/%d = -1",a,b,c,d);
	else
		printf("%d/%d - %d/%d = %d/%d\n",a,b,c,d,fenzi,fenmu);
} 


void multiply(int a,int b,int c,int d)
{
	int fenzi,fenmu;
	int g;
	fenzi = a * c;
	fenmu = b * d;
	g = Gcd(fenmu,fenzi);
	fenmu = fenmu / g;
	fenzi = fenzi / g;
	if(fenzi == 0 || fenmu == 1)
		printf("%d/%d * %d/%d = %d\n",a,b,c,d,fenzi);
	else 
		printf("%d/%d * %d/%d = %d/%d\n",a,b,c,d,fenzi,fenmu);
} 

void divide(int a,int b,int c,int d)
{
	int fenzi,fenmu;
	int g;
	fenzi = a * d;
	fenmu = b * c;
	g = Gcd(fenzi,fenmu);
	fenmu = fenmu / g;
	fenzi = fenzi / g;
	printf("%d/%d / %d/%d = %d/%d\n",a,b,c,d,fenzi,fenmu);
}



int main()
{
	int a,b,c,d;
	char s;
	scanf("%d %d %c %d %d",&a,&b,&s,&c,&d);
	if(b == 0 || d == 0)
	{
		printf("Input error.Zero cannot be a denominator\n");	
	}else
	{
		switch(s)
		{
			case '+': plus(a,b,c,d);     break;
			case '-': minus(a,b,c,d);    break;
			case '*': multiply(a,b,c,d); break;
			case '/': divide(a,b,c,d);   break;
		}	
	}
	
	return 1;
} 

标签:分数,Gcd,int,四则运算,else,fenmu,printf,fenzi
来源: https://www.cnblogs.com/akmfwei/p/13597084.html