题目链接:Repeating Decimals
题目描述:
输入整数a和b(0<=a<=3000,1<=b<=3000),输出a/b的循环小数表示以及其循环节长度,例如a=5,b=43,小数表示为0.(116279069767441860465),循环节长度为21.
本题实际上模拟长除法的计算过程,其中每一次除法时都有被除数和余数,当被除数出现重复时就表示出现循环节,所以需要记录每一次的被除数及其在循环小数中的位置,需要时注意当除数不够除,每一次补零也需要记录其对应位置。
map的使用:https://blog.csdn.net/newyoung518/article/details/16118141
assert定义和用法:https://blog.csdn.net/aaa123524457/article/details/78780267
代码实现:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<map> //定义map()
#include<assert.h> // 定义assert()
#include<algorithm>
using namespace std;
const int Maxsize=3005;
map<int,int> Pos;
void solve(int n,const int d,string& ans,int &r)
{
assert(n%d&&n<d);
ans='.';
Pos.clear();
while(true)
{
n*=10;
int p=Pos[n];
if(p==0)Pos[n]=ans.size();
else
{
r=ans.size()-p;
if(r>50)
{
ans.erase(p+50);
ans+="...";
}
ans.insert(p,"(");
ans+=')';
break;
}
if(n<d)
{
ans+='0';
continue;
}
int div=n/d,mod=n%d;
ans+=(char)(div+'0');
n=mod;
if(n==0)
{
ans+="(0)";
r=1;
break;
}
}
}
int main()
{
int a,b;
while(scanf("%d%d",&a,&b)==2)
{
string ans=".(0)";
int r=1;
if(a%b)
solve(a%b,b,ans,r);
printf("%d/%d = %d%s\n",a,b,a/b,ans.c_str());
printf(" %d = number of digits in repeating cycle\n\n",r);
}
return 0;
}