Home > OS >  converting a fraction into a decimal
converting a fraction into a decimal

Time:09-28

I'm doing a project and need to multiply 2 fractions into a decimal. I've tried everything i can think of but run into errors like 'could not convert string to float' any advice?

num1 = int(input ('Enter the first numerator'))
den1 = int(input ('Enter the first denominator'))
num2 = int(input ('Enter the second numerator'))
den2 = int(input ('Enter the second denominator'))
newnum = ('num1 * num2')
newden = ('den1 * den2')

print (f'The fractional answer is {num1 * num2} / {den1 * den2}')
print (f'The decimal answer is {newnum / newden}')

CodePudding user response:

Did you try getting rid of the single quotes around ('num1 * num2') and ('den1 * den2'). I'm pretty sure you are setting newnum equal to a string not a float when you have the single quotes around it.

CodePudding user response:

As another answer suggests, remove the quotes from (num1 * num2) and (den1 * den2), because the current code assigns to a string.

I would also mention that this is a really weird way to do it and the following would be much more pythonic:

*edit: apparently fstrings are a new thing and all shiny but many people are probably much more used to .format()

num1 = int(input('First numerator: '))
den1 = int(input('First denominator: '))
num2 = int(input('Second numerator: '))
den2 = int(input('Second denominator: '))
newnum = num1 * num2
newden = den1 * den2

print('The fractional answer is: '   str(newnum)   '/'   str(newden))
print('The decimal answer is: '   str(newnum / newden))

Most would further simplify it to:

new_numerator = int(input('First numerator: ')) * int(input('First denominator: '))
new_denomitor = int(input('Second numerator: ')) * int(input('Second denominator: '))

print('The fractional answer is: '   str(new_numerator)   '/'   str(new_denomitor))
print('The decimal answer is: '   str(new_numerator / new_denomitor))

and many would do:

new_numerator = int(input('First numerator: ')) * int(input('First denominator: '))
new_denomitor = int(input('Second numerator: ')) * int(input('Second denominator: '))

print('The fractional answer is: {}/{}'.format(new_numerator, new_denomitor))
print('The decimal answer is: '   str(new_numerator / new_denomitor))

if you go and use fstrings:

new_numerator = int(input('First numerator: ')) * int(input('First denominator: '))
new_denomitor = int(input('Second numerator: ')) * int(input('Second denominator: '))

print(f'The fractional answer is: {new_numerator}/{new_denomitor}')
print('The decimal answer is: '   str(new_numerator / new_denomitor))
  • Related