from fractions import Fraction
# Convert decimal to fraction
decimal_number = input("Enter a Decimal Number:")
fraction_result = Fraction(decimal_number).limit_denominator()
print(f"Decimal: {decimal_number}")
print(f"Fraction: {fraction_result}")
#clcoding.com for free code visit
Explanation :
Let's break down the code step by step:
from fractions import Fraction
This line imports the Fraction class from the fractions module. The Fraction class is used to represent and perform operations with rational numbers.
# Convert decimal to fraction
decimal_number = input("Enter a Decimal Number:")
This line prompts the user to enter a decimal number by using the input function. The entered value is stored in the variable decimal_number.
fraction_result = Fraction(decimal_number).limit_denominator()
Here, the entered decimal_number is converted to a Fraction object using the Fraction class. The limit_denominator() method is then called to limit the denominator of the fraction to a reasonable size.
print(f"Decimal: {decimal_number}")
print(f"Fraction: {fraction_result}")
These lines print the original decimal number entered by the user and the corresponding fraction.
#clcoding.com for free code visit
This line is a comment and is not executed as part of the program. It's just a comment providing a website link.
So, when you run this code, it will prompt you to enter a decimal number, convert it to a fraction, and then print both the original decimal and the corresponding fraction. The limit_denominator() method is used to present the fraction in a simplified form with a limited denominator.
0 Comments:
Post a Comment