描述
写一个程序…可以实现在连分数和分数之间的互相转换…
样例1
样例输入1
[2;3,7]
51/22
样例输出1
51/22
[2;3,7]
提示
多组测试数据:
…每一个测试点有多组数据…数据的组数不超过100组…
约分:
计算结果最后是要约分的…但是…在分数转向连分数的时候…
我们不保证输入的数据是约分…
连分数的输入格式:
连分数的输入格式是按照wiki里写的…
第一个位置的分号应该是为了避免可能的歧义~…
Range:
数字的规模都很小…
也就是它们都不会超过longint范围里…
包括中间的数据…
连分数的项数也不会超过100项…
#include <iostream>
#include <string>
#include <memory.h>
using namespace std;
string s;
int main()
{
std::ios::sync_with_stdio(false);
while (cin >> s)
{
int a[100], t = 0;
bool flag = false;
memset(a, 0, sizeof(a));
if (s[0] == '[')
{
for (int i = 1; i < s.size(); i++)
{
if (s[i] >= '0'&&s[i] <= '9')
{
flag = true;
a[t] = a[t] * 10 + (int)(s[i] - '0');
}
else
{
t++;
flag = false;
}
}
int x = a[t], y = 1;
for (int i = t; i >= 0; i--)
{
int temp = x;
x = y + a[i] * x;
y = temp;
}
int max = x, min = y;
while (max%min != 0)
{
int temp = min;
min = max%min;
max = temp;
}
x = x / min, y = y / min;
if (y == 1)
cout << x << endl;
else
cout << x << "/" << y << endl;
}
else
{
for (int i = 0; i < s.size(); i++)
{
if (s[i] >= '0'&&s[i] <= '9')
{
flag = true;
a[t] = a[t] * 10 + (int)(s[i] - '0');
}
else
t++;
}
if (t == 0)
cout << '[' << a[0] << ']' << endl;
else
{
int max = a[0], min = a[1];
while (max%min != 0)
{
int temp = min;
min = max%min;
max = temp;
}
int x = a[0] / min, y = a[1] / min;
t = 0;
cout << "[";
while (x != 1)
{
int div = x / y, rem = x%y;
if (t == 0)
cout << div;
else
if (t == 1)
cout << ";" << div;
else
cout << "," << div;
x = rem;
if (x != 1)
{
int temp = y;
y = x;
x = temp;
}
t++;
}
if (y != 0)
cout << ',' << y;
cout << ']' << endl;
}
}
}
return 0;
}