分数化小数 Fractions to Decimals
生活随笔
收集整理的這篇文章主要介紹了
分数化小数 Fractions to Decimals
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
https://www.luogu.org/problemnew/show/P1530
題解:模擬除法
/* *@Author: STZG *@Language: C++ */ #include <bits/stdc++.h> #include<iostream> #include<algorithm> #include<cstdlib> #include<cstring> #include<cstdio> #include<string> #include<vector> #include<bitset> #include<queue> #include<deque> #include<stack> #include<cmath> #include<list> #include<map> #include<set> //#define DEBUG #define RI register int #define endl "\n" using namespace std; typedef long long ll; //typedef __int128 lll; const int N=100000+10; const int M=100000+10; const int MOD=1e9+7; const double PI = acos(-1.0); const double EXP = 1E-8; const int INF = 0x3f3f3f3f; int t,n,m,k,p,l,r,u,v,d,w; int cnt,flag,temp,sum; string ans; int pd[N]; char str; struct node{}; int main() { #ifdef DEBUGfreopen("input.in", "r", stdin);//freopen("output.out", "w", stdout); #endif//ios::sync_with_stdio(false);//cin.tie(0);//cout.tie(0);//scanf("%d",&t);//while(t--){scanf("%d%d",&n,&d);k=n/d,w=-1;do{ans=char(k%10+'0')+ans;//這種方法要把拆分出來的整數(shù)放到前面去,不然會反過來,因?yàn)樗炔鸱謧€位,再拆分十位,直接加會使個位在前,直接加會使十位在后,k/=10;}while(k>0);//拆分結(jié)果的整數(shù)部分進(jìn)ans。由于0也算是整數(shù)部分,所以無論如何也要拆分一次,用do{}while(),不然用for() 整數(shù)部分為0時就不會拆進(jìn)去,因?yàn)閗=0了ans+='.';//鑒于結(jié)果無論如何至少有一位小數(shù),加個小數(shù)點(diǎn)n=n%d;//被除數(shù)取余,開始模擬小數(shù)部分的除法運(yùn)算do{if(pd[n]!=0){w=pd[n];break;}//如果余數(shù)有重復(fù),說明這是一個循環(huán)小數(shù),上一個n出現(xiàn)的位置便是循環(huán)節(jié)開始(左括號)的位置else pd[n]=ans.size();//否則就記下這個余數(shù)變?yōu)楸怀龜?shù)后對應(yīng)的商出現(xiàn)的位置,以便未來判斷和記錄n*=10;//n變成被除數(shù),末尾加0(N,D一定是正整數(shù),不存在小數(shù)可加在末尾)k=n/d;ans+=char(k+'0');n=n%d;//模擬除法}while(n!=0);//由于結(jié)果如果是正整數(shù)的話,末尾也得加0,用do()while{}if(w!=-1) ans+=')';//如果結(jié)果是一個循環(huán)小數(shù),在末尾加個右括號,便于輸出int len=ans.size();for(int i=0;i<len;i++){if(i==w){putchar('(');i--;w=-1;}//如果這個地方是循環(huán)節(jié)的開頭,在這里輸出左括號,并將w改為-1,避免重復(fù)輸出括號,同時i--,因?yàn)檫@里的ans[i]還沒輸出else putchar(ans[i]);sum++;if(sum%76==0) putchar('\n');//putchar( )可理解為cout<<char( );}//注:我這樣處理循環(huán)節(jié)的開頭是為了便于換行,因?yàn)樽罄ㄌ栆菜闶亲址?/}#ifdef DEBUGprintf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC); #endif//cout << "Hello world!" << endl;return 0; }?
總結(jié)
以上是生活随笔為你收集整理的分数化小数 Fractions to Decimals的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回家 Bessie Come Home
- 下一篇: 最短网络 Agri-Net