PAT 1081. Rational Sum

13级何班机考题,字符串模拟分数加法。


1. 结果为0时输出0

2. 结果为整数时输出整数

3. 结果为假分数时输出"整数 分子/分母"

4. 注意结果为负的情况

5. 化简。题目只考察了最终结果的化简,最好是对每一个输入及中间结果都进行化简,以免溢出。


代码(第二次):

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

long long string_to_long(const string& str)
{
	long long ret;
	stringstream ss;
	ss << str;
	ss >> ret;
	return ret;
}

void simplify(long long& a1, long long&b1)
{
	for (long long i = 2; i<=abs(a1) && i<abs(b1); ++ i)
	{
		for ( ; a1%i==0 && b1%i==0; a1/=i, b1/=i) {}
	}
}

int main()
{
	int n;
	string num;
	long long a_numerator, a_denominator, b_numerator, b_denominator;
	cin >> n;
	cin >> num;
	size_t pos = num.find('/');
	a_numerator = string_to_long( num.substr(0, pos) );
	a_denominator = string_to_long( num.substr(pos+1) );

	for (int i = 1; i < n; ++ i)
	{
		cin >> num;
		pos = num.find('/');
		b_numerator = string_to_long( num.substr(0, pos) );
		b_denominator = string_to_long( num.substr(pos+1) );
		a_numerator = (a_numerator*b_denominator + b_numerator*a_denominator);
		a_denominator = a_denominator * b_denominator;
		simplify(a_numerator, a_denominator);
	}

	if (a_numerator < 0)
	{
		cout << "-";
		a_numerator = -a_numerator;
	}
	if (a_numerator % a_denominator == 0)
	{
		cout << a_numerator;
	} else if (a_numerator < a_denominator)
	{
		cout << a_numerator << "/" << a_denominator;
	} else
	{
		cout << a_numerator/a_denominator << " " << a_numerator%a_denominator << "/" << a_denominator;
	}

	return 0;
}



代码 (第一次):

#include <iostream>
#include <string>
#include <sstream>
#include <cmath>

using namespace std;

long long string_to_long(const string& str)
{
	long long ret;
	stringstream ss;
	ss << str;
	ss >> ret;
	return ret;
}

string long_to_string(const long long num)
{
	stringstream ss;
	ss << num;
	return ss.str();
}

void simplify(long long& a1, long long&b1)
{
	for (long long i = 2; i<abs(a1) && i<abs(b1); ++ i) // 这里需要使用abs, 用以处理负数的化简,谢谢cn_goku的指正
	{
		for ( ; a1%i==0 && b1%i==0; a1/=i, b1/=i) {} 
	}	
}

int main()
{
	int n;
	string now, next;

	cin >> n;
	cin >> now;
	for (int i = 1; i < n; ++ i)
	{
		cin >> next;
		long long a1 = string_to_long(now.substr(0, now.find('/')));
		long long b1 = string_to_long(now.substr(now.find('/')+1));
		long long a2 = string_to_long(next.substr(0, next.find('/')));
		long long b2 = string_to_long(next.substr(next.find('/')+1));
		long long numerator = (a1*b2+a2*b1);
		long long denominator = (b1*b2);
		simplify(numerator, denominator);
		now = long_to_string(numerator) + "/" + long_to_string(denominator);
	}
	long long a1 = string_to_long(now.substr(0, now.find('/')));
	long long b1 = string_to_long(now.substr(now.find('/')+1));
	simplify(a1, b1);
	if (a1 == 0)
	{
		cout << 0;
	} else
	{
		if (a1 / b1 != 0)
		{
			cout << a1/b1;
			a1 = a1%b1;
			a1 = abs(a1);
			if (a1 == 0)
			{
				return 0;
			} else
			{
				cout << " ";
			}
		}
		cout << a1 << "/" << b1 << endl;
	}

	return 0;
}


你可能感兴趣的:(C++,pat)