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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值