python - Wrong results for calculator subtraction and division -


my addition , multiplication work fine. however, subtraction, if input 2 numbers, 3 , 1, answer -2, incorrect. division not functioning properly.

i can input 2 numbers, 8 , 4, , tell me answer 0.5, incorrect.

what went wrong in code?

print("welcome calculator!")  class calculator:     def addition(self,x,y):         added = x + y         return added     def subtraction(self,x,y):         subtracted = x - y         return subtracted     def multiplication(self,x,y):         multiplied = x * y         return multiplied     def division(self,x,y):         divided = x / y         return divided  calculator = calculator()  print("1 \taddition") print("2 \tsubtraction") print("3 \tmultiplication") print("4 \tdivision") operations = int(input("what operation use?:  "))  x = int(input("how many numbers use?:  "))  if operations == 1:     = 0     sum = 0     while < x:         number = int(input("please enter number here:  "))         += 1         sum = calculator.addition(number,sum)     print("the answer is", sum) if operations == 2:     s = 0     diff = 0     while s < x:         number = int(input("please enter number here:  "))         s += 1         diff = calculator.subtraction(number,diff)     print("the answer is", diff) if operations == 3:     m = 0     prod = 1     while m < x:         number = int(input("please enter number here:  "))         m += 1         prod = calculator.multiplication(number, prod)     print("the answer is", prod) if operations == 4:     d = 0     quo = 1     while d < x:         number = int(input("please enter number here:  "))         d += 1         quo = calculator.division(number, quo)     print("the answer is", quo) 

if operations == 4:     d = 0     quo = 1     while d < x:         number = int(input("please enter number here:  "))         d += 1         quo = calculator.division(number, quo)     print("the answer is", quo) 

the first time through quo becomes 8. goes through again 4 number , 8 quo. 4 / 8 = .5

here's alternative solution using reduce functools library.

if operations == 4:     quo = 1     numbers = list()     while len(numbers) < x:         number = int(input("please enter number here:  "))         numbers.append(number)     quo = reduce(calculator.division, numbers)     print("the answer is", quo) 

i'd know why downvoted when indeed answer why division wasn't working...


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -