[编程之美_2.6]精确表达浮点数

以下代码将问题简化为求无限循环小数的分数,至于有限的直接改成分数即可,不过涉及到另一个重要知识,就是求最大公约数,比较经典的是辗转相除法。
代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// GCD
int GCD(int x, int y)
{
   return y == 0 ? x : GCD(y, x % y);
}

// Simplified conditions
// x: 无限循环小数
// n: 循环节的整数表示
// m: 循环节长度
// 10^m * x = n + x
// x = n / (10^m - 1)
void FloatNumber(string number)
{
   int start = number.find_first_of('(') + 1;
   int end = number.find_first_of(')');
   string repetend = number.substr(start, end - start);
   int n = atoi(repetend.c_str());
   int m = end - start;
   int d = GCD(n, ((int)pow(10.0, m) - 1));
   cout << n / d << '/' << ((int)pow(10.0, m) - 1) / d << endl;
}