The code below simplifies the problem to converting a repeating decimal into a fraction. For terminating decimals, you can convert them directly to fractions, but this involves another important concept: finding the greatest common divisor (GCD). The classic method is the Euclidean algorithm.
Code:
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: repeating decimal
// n: integer representation of the repeating block
// m: length of the repeating block
// 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;
}
|