UVa 202 Repeating Decimal

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size:18px;">问题:求一个有理数的循环周期。</span></span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size:18px;">思路:余数出现分母次后,只少会有两次是相同的</span></span>

  流程:①读取分子,分母;

              ②取模、取余、乘10,放到一个结构数组中

              ③每取一个余数,都要到结构中查一下是否有相同的值

              ④这两个值之间的值就是周期。

              ⑤根据格式输出周期

              ⑥如果超过50,使用省略号。

Trick:OJ上最后结果添加了一个空行,提交了好几次总是PresentationE,神奇。


#include<iostream>
#include<string>
#include<iomanip>

using namespace std;

typedef struct {
	int factor;
	int remainder;
} Elem;

int main()
{
#ifndef UVa
	FILE *fp;
	freopen_s(&fp, "data.in.txt", "r", stdin);
	freopen_s(&fp, "data.out.txt", "w", stdout);
#endif

	Elem *eArr = new Elem[3000];
	int numerator = 0;
	int denominator = 0;
	int cnt = 0;
	
	while (cin >> numerator >> denominator) {
		int pos1 = -1,pos2 = -1;
		if (cnt++ > 0)
			cout << endl;
		cout << numerator << "/" << denominator << " = ";
		for (int i = 0; i < 3000; ++i) {
			eArr[i].factor = numerator / denominator;
			numerator %= denominator;
			eArr[i].remainder = numerator;
			numerator *= 10;
			for (int j = 0; j < i; ++j) 
				if (eArr[i].remainder == eArr[j].remainder) {
					pos1 = j;
					pos2 = i;
					break;
				}
				else {
					pos1 = -1;
					pos2 = -1;
				}//endif
			if (pos1 != -1 && pos2 != -1)
					break;
		}//endfor
		
		cout << eArr[0].factor << ".";
        int index = 0;
		for (index = 1; index <= pos1; ++index)
			cout << eArr[index].factor;
		cout << "(";
		
		for (; index <= pos2; ++index ) {
			cout << eArr[index].factor;
			if (index == 50)
				break;
		}
		if (index == 50)
			cout << "...";
		cout << ")" << endl;
		cout << "   " << setiosflags(ios::left) << pos2 - pos1 << " = number of digits in repeating cycle" << endl;
	}
	cout << endl;
    return 0;
}




阅读更多
个人分类: UVa
上一篇UVa1368 DNA Consensus String
下一篇UVa 10340 All inAll
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭