编程之美2.6――精确表达浮点数(二)

2014-11-24 11:51:23 · 作者: · 浏览: 5
到商c
d.len = 1; d.s[1] = 0;
for (i=a.len; i>0; i--)
{
if (!(d.len == 1 && d.s[1] == 0))
{
// i没移一位,余数d也移位
for (j=d.len; j>0; j--)
d.s[j+1] = d.s[j];
d.len++;
}
d.s[1] = a.s[i];
c.s[i] = 0;
// 余数d大于除数b时,才可以进行减操作
while ((j=HPCompare(d,b)) >= 0)
{
Subtract(d, b, d);
c.s[i]++;
if (j == 0) break;
}
}
c.len = a.len;
while (c.len > 1 && c.s[c.len] == 0)
c.len--;
}
// 十进位右移
void RightShift(HP &x, int k)
{
for (int i=1; i<=x.len-k; i++)
x.s[i] = x.s[i+k];
x.len -= k;
if(x.len <= 0)
{
x.len = 1;
x.s[1] = 0;
}
}
// 十进位左移
void LeftShift(HP &x, int k)
{
int i;
for (i=x.len; i>=1; i--)
x.s[i+k] = x.s[i];
for (i=k; i>=1; i--)
x.s[i] = 0;
x.len += k;
}
// 求大整数的最大公约数
void GCD(HP a, HP b, HP &c)
{
if (b.len == 1 && b.s[1] == 0)
{
c.len = a.len;
memcpy(c.s, a.s, (a.len+1)*sizeof(int));
}
else
{
HP m, n;
Divide(a, b, m, n);
GCD(b, n, c);
}
}

int main()
{
string str;
string strc, stra, strb;
cin >> str;
int posc = str.find('.');
int posa = str.find('(');
int posb = str.find(')');
strc = str.substr(0, posc);
if (posc < 0)
cout << strc;
else
{
HP a, b, c;
HP tmp; tmp.len = 1; tmp.s[1] = 1;
// 整数部分
Str2HP(strc.c_str(), c);
stra = str.substr(posc+1, posa-posc-1);
// 非循环部分
Str2HP(stra.c_str(), a);
// up分子,down分母
HP up = c, down = tmp;
// 乘以10^|a|
LeftShift(down, stra.size());
LeftShift(up, stra.size());
Plus(up, a, up);
if (posa >= 0)
{
strb = str.substr(posa+1, posb-posa-1);
// 循环部分
Str2HP(strb.c_str(), b);
HP m = tmp;
LeftShift(m, strb.size());
Subtract(m, tmp, m);
// 乘以10^(|b|-1)
Multi(up, m, up);
Plus(up, b, up);
Multi(down, m, down);
}
// 求分子分母的最大公约数
GCD(down, up, tmp);
HP h;
Divide(down, tmp, down, h);
Divide(up, tmp, up, h);
PrintHP(up); cout << "/";
PrintHP(down); cout << endl;
}
}
作者:linyunzju