欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PAT乙级考试-1034 有理数四则运算 (20分)

程序员文章站 2022-06-13 15:42:28
...

题目
PAT乙级考试-1034 有理数四则运算 (20分)
PAT乙级考试-1034 有理数四则运算 (20分)
思路
本题的关键是要知道怎么求最大公约数来进行化简,这里采用辗转相除法来计算。知道如何化简后,依次录入,化简,计算,打印即可

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct
{
	long long int fz;
	long long int fm;
	long long int zs;
}number;

long long int gy(long long int i, long long int j)
{
	long long int k;
	while (i % j != 0)
	{
		k = i % j;
		i = j;
		j = k;
	}
	return abs(j);
}

void trans(char temp[], number* a)
{
	char* flag = strchr(temp, '-');
	long long int i = 0, j = 0;
	long long int k = flag ? 1 : 0;
	for (; temp[k] != '/'; k++)
		i = i * 10 + temp[k] - '0';
	for (k = k + 1; temp[k] != '\0'; k++)
		j = j * 10 + temp[k] - '0';
	long long int e = gy(i, j);
	k = flag ? -1 : 1;
	i = (i * k) / e;
	j = j / e;
	a->zs = i / j;
	a->fz = i % j;
	a->fm = j;
}

void print(number a)
{
	long long int flag = 0;
	if (a.zs == 0 && a.fz == 0)
	{
		printf("0");
		return;
	}
	if (a.fm == 0)
	{
		printf("Inf");
		return;
	}
	if (a.fz < 0 || a.zs < 0)
	{
		flag = 1;
		printf("(-");
		a.zs = -a.zs;
		a.fz = -a.fz;
	}
	if (a.zs != 0)
		printf("%d", a.zs);
	if (a.fz != 0)
	{
		if (a.zs != 0)
			printf(" ");
		if (a.fm == 1)
			printf("%d", a.fz);
		else
			printf("%d/%d", a.fz, a.fm);
	}
	if (flag)
		printf(")");
}

number compute(number a, number b, char ch)
{
	long long int z, m, l, e, temp;
	a.fz = a.zs * a.fm + a.fz;
	b.fz = b.zs * b.fm + b.fz;
	number c;
	if (ch == '+')
	{
		m = a.fm * b.fm;
		z = a.fz * b.fm + b.fz * a.fm;
	}
	else if (ch == '-')
	{
		m = a.fm * b.fm;
		z = a.fz * b.fm - b.fz * a.fm;
	}
	else if (ch == '*')
	{
		m = a.fm * b.fm;
		z = a.fz * b.fz;
	}
	else
	{
		if (b.fz == 0)
			m = 0;
		else
		{
			if (b.fz > 0)
			{
				temp = b.fz;
				b.fz = b.fm;
				b.fm = temp;
			}
			else
			{
				temp = b.fz;
				b.fz = -b.fm;
				b.fm = -temp;
			}
			m = a.fm * b.fm;
			z = a.fz * b.fz;
		}
	}
	if (m != 0)
	{
		e = gy(z, m);
		z = z / e;
		m = m / e;
		c.zs = z / m;
		c.fz = z % m;
		c.fm = m;
	}
	else
		c.fm = 0;
	return c;
}

 int main(void)
{
	char temp1[50], temp2[50];
	scanf("%s%s", temp1, temp2);
	number a, b, c;
	trans(temp1, &a);
	trans(temp2, &b);
	char op[4] = { '+','-','*','/' };
	for (long long int i = 0; i < 4; i++)
	{
		print(a);
		printf(" %c ", op[i]);
		print(b);
		c = compute(a, b, op[i]);
		printf(" = ");
		print(c);
		printf("\n");
	}
	return 0;
}