- 数与连分数
- 2017-08-12 21:48:46 @
#include <bits/stdc++.h>
using namespace std;
string s;
int a[1000],i,j,k,l,n,fz,fm;
int gcd(int a,int b)
{
int r = a % b;
while(r != 0)
{
a = b;
b = r;
r = a % b;
}
return b;
}
int main()
{
while(cin >> s)
{
if (s[0] == '[')
{
s.erase(s.size()-1,1);
s += ",]";
k = s.find(';');
for (i = 1; i < k; i++)
a[1] = a[1] * 10 + int(s[i]) - 48;
s.erase(0,k + 1);
j = 1;
while(s[0] != ']')
{
k = s.find(',');
j++;
for (i = 0; i < k; i++)
a[j] = a[j] * 10 + int(s[i]) - 48;
s.erase(0,k + 1);
}
n = j;
fz = 0;
fm = 1;
for (i = n; i > 0; i--)
{
fz += a[i] * fm;
swap(fz,fm);
}
k = gcd(fz,fm);
fz /= k;
fm /= k;
cout << fm << "/" << fz << endl;
}
else
{
fz = 0;
fm = 0;
k = s.find('/');
for (i = 0; i < k; i++)
fz = fz * 10 + int(s[i]) - 48;
for (i = k + 1; i < int(s.size()); i++)
fm = fm * 10 + int(s[i]) - 48;
k = gcd(fz,fm);
fz /= k;
fm /= k;
i = 0;
cout << "[";
while(fz != 1)
{
int div = fz / fm,mod = fz % fm;
if(i == 0)
cout << div;
else
if(i == 1)
cout << ";" << div;
else
cout << "," << div;
fz = mod;
if(fz != 1)
swap(fz,fm);
i++;
}
if(fm != 0)
cout << "," << fm;
cout << "]" << endl;
}
}
return 0;
}
谢各位大佬!!!
0 条评论
目前还没有评论...