To convert a decimal to fraction we express the decimal as a ratio of two integers (a numerator and a denominator). The process can be different depending on the decimal's characteristics.
Let's say you have a decimal number, such as 0.75.
Count the number of decimal places in the given decimal. In our example (0.75), there are two decimal places.
For 0.75:
So, 0.75 as a fraction is 75/100.
If possible, simplify the fraction by finding the greatest common divisor (GCD) of the numerator and the denominator, and then dividing both by the GCD.
In our example, the GCD of 75 and 100 is 25. Dividing both the numerator and denominator by 25 results in:
75 ÷ 25 = 3
100 ÷ 25 = 4
So, the simplified fraction is 3/4.
Keep in mind that not all decimals can be easily converted to fractions, especially repeating decimals (those that have a repeating pattern of digits after the decimal point). In such cases, the conversion might involve more complex techniques, such as using algebra or long division.
Let's create an ANSI C function decimalToFraction. It will convert a decimal number to a fraction and then simplify it. When we run it, the output should look like this:
void decimalToFraction(double decimal) { // Scale the decimal to handle more precision int numerator = (int)(decimal * 1000000); int denominator = 1000000; // Find the greatest common divisor int gcd = getGCD(numerator, denominator); // Simplify the fraction numerator /= gcd; denominator /= gcd; printf("Decimal: %.6lf\n", decimal); printf("Fraction: %d / %d\n", numerator, denominator); // Simplify the fraction further int wholePart = numerator / denominator; int remainderNumerator = numerator % denominator; printf("Simplified Fraction: %d and %d/%d\n", wholePart, remainderNumerator, denominator); }
Here's a step-by-step explanation of what the function does:
Overall, this function performs the conversion from a decimal to a fraction, simplifies the fraction, and provides both the raw fraction form and a mixed number representation of the simplified fraction.
int getGCD(int a, int b) { if (b == 0) { return a; } return getGCD(b, a % b); }
The C function getGCD calculates the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm, a well-known algorithm for finding the greatest common divisor efficiently. Here's how the function works:
The algorithm utilizes the fact that the GCD of two numbers remains the same if the larger number is replaced by the remainder of its division by the smaller number. This property allows the algorithm to iteratively reduce the problem until it reaches the base case, where the GCD is found.
Overall, the function efficiently calculates the GCD of two integers using recursion and the properties of the Euclidean algorithm.
A whole working program, using the functions above is located at my github page.
To get all examples use:
git clone https://github.com/ProgrammingSimpleSteps/c-examples.git