usaco分数化小数

写一个程序,输入一个形如 N/D 的分数(N 是分子,D 是分母),输出它的小数形式。
如果小数有循环节的话,把循环节放在一对圆括号中。例如,
1/3 = .33333333 写成 0.(3)
41/333 = 0.123123123... 写成 0.(123)
用 xxx.0 成表示整数
典型的转化例子:
1/3 = 0.(3)
22/5 = 4.4
1/7 = 0.(142857)
2/2 = 1.0
3/8 = 0.375

45/56 = 0.803(571428)


对于做出这道题我表示心很累,对多种情况的处理和细节分析都感觉有些麻烦,

言归正传,思路的关键,主要是找循环节,我们可以通过求余来判断,因为只要除到某一位置,所得余数和曾经的某个地方一样,这一串就是所求循环节

这种题多试试,要找出求解的根源,即此题的普遍性,来减少特判,并且特判多了其实就是有细节没有考虑上。还是要找普遍性

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
using namespace std;
int n,d,a[1000009],h[1000009],tot=0;
bool b[1000009];
void write(int a)
{
	printf("%d",a);
	tot++;if (tot==76) tot=0,printf("\n");
}
int main()
{
	scanf("%d%d",&n,&d);
	printf("%d.",n/d);
	int rt=n/d;if (rt==0)tot=1;
	while (rt) tot++,rt=rt/10;
	tot++;
	int j=0,i=0;
	n=n%d;if (n==0)printf("0");
	while(n)
	{
		i++;
		if (!b[n])
		{
			b[n]=true;
			h[n]=i;
		}else 
		{
			j=h[n];
			break;
		}
		n=n*10;
		a[i]=n/d;
		n=n%d;
	}
	int m=i;
	if (j)
	{
		for (i=1;i<j;i++) write(a[i]);
		printf("(");tot++;if (tot==76) printf("\n"),tot=0;
		for (i=j;i<m;i++) write(a[i]);
		printf(")");tot++;if (tot==76) printf("\n"),tot=0;
	}else for (int i=1;i<=m;i++)write(a[i]);

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值