- 数与连分数
- 2019-04-04 16:18:07 @
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stack>
#include <queue>
using namespace std;
int gys(int a,int b){
if(a<b) swap(a,b);
int r=a%b;
while(r){
a=b;
b=r;
r=a%b;
}
return b;
}
int main()
{
string t;
while(getline(cin,t)){
if(t[0]=='['){
int d; char c;
stringstream ss(t);
stack<int> s; ss>>c;
while(ss>>d>>c) s.push(d);
int fz=0,fm=1; //从浅入深
while(!s.empty()){
int p=s.top(); s.pop();
fz+=p*fm;
swap(fz,fm);
}
swap(fz,fm);
int g=gys(fz,fm);
fz/=g; fm/=g;
if(fm==1) cout<<fz<<endl;
else cout<<fz<<"/"<<fm<<endl;
}else{
stringstream ss(t);
if(t.size()==1){cout<<"["<<t<<"]\n"; return 0;}
int fz,fm; char c;
ss>>fz>>c>>fm;
int g=gys(fz,fm);
fz/=g; fm/=g;
queue<int> q;
while(1){
q.push(fz/fm);
fz=fz%fm;
if(fz==1){q.push(fm); break;}
else if(fz==0) break;
swap(fz,fm);
}
if(q.size()==1){cout<<"["<<q.front()<<"]\n"; return 0;}
int len=q.size(); //pop时size会改变 先赋值给len
for(int i=0;i<len;++i){
int p=q.front(); q.pop();
if(i==0) cout<<"["<<p<<";";
else if(i==len-1) cout<<p<<"]\n";
else cout<<p<<",";
}
}
}
return 0;
}
0 条评论
目前还没有评论...