Convert Ratio To Decimal
May 15, 2015
Here’s our solution, which was indeed written within fifteen minutes:
(define (decimal num denom digits)
(let loop ((num (* (modulo num denom) 10))
(out (cons #\. (reverse (string->list
(number->string (quotient num denom))))))
(digits digits))
(if (zero? digits)
(list->string (reverse out))
(loop (* (modulo num denom) 10)
(cons (integer->char (+ (quotient num denom) 48)) out)
(- digits 1)))))
This is nothing more than the grade-school long-division algorithm, generating the output one digit at a time; out
is initialized to the part of the quotient to the left of the decimal point, in reverse:
> (decimal 3227 557 30)
"5.793536804308797127468581687612"
You can run the program at http://ideone.com/hiNpKQ.
In Python.
A quick ‘n dirty Haskell version.
A couple of examples in ghci:
In C++
#include
using namespace std;
int main()
{
int den,num,dig,temp1,temp2;
cout <> den;
cout <> num;
cout <> dig;
cout << num/den << "."; // Whole number part of decimal followed by decimal point
temp1=num;
for (int i=0;i<30;i++)
{
temp2=(temp1%den)*10;
cout << temp2/den;
temp1=temp2%den;
}
return 0;
}
In C++
Clojure
I admit, it took me longer than 15 minutes..