Thursday 15 April 2010

algorithm - Converting decimal to fraction c++ -



algorithm - Converting decimal to fraction c++ -

what algorithm can utilize convert , input decimal number fraction form in c++. illustration if come in 1.25 conversion output 1 1/4.

first fractional part , take gcd. utilize euclidean algorithm http://en.wikipedia.org/wiki/euclidean_algorithm

void foo(double input) { double integral = std::floor(input); double frac = input - integral; const long precision = 1000000000; // accuracy. long gcd_ = gcd(round(frac * precision), precision); long denominator = precision / gcd_; long numerator = round(frac * precision) / gcd_; std::cout << integral << " + "; std::cout << numerator << " / " << denominator << std::endl; } long gcd(long a, long b) { if (a == 0) homecoming b; else if (b == 0) homecoming a; if (a < b) homecoming gcd(a, b % a); else homecoming gcd(b, % b); }

c++ algorithm

No comments:

Post a Comment