Convert Ratio To Decimal
May 15, 2015
Our exercise today is an interview question. Like all of our interview questions, it works better if you put some pressure on yourself to simulate the pressure of an interview; so, for today’s exercise you must complete your solution in fifteen minutes:
Given two positive integers, a numerator and a denominator, and a third positive integer, the number of digits, write the decimal ratio of numerator to denominator to the requested number of digits. For instance, given a numerator of 3227, a denominator of 557, and a number of digits of 30, the correct output is 5.793536804308797127468581687612.
Your task is to write a program to convert ratios to decimals. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
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..