问题
My addition and multiplication work just fine. However, for subtraction, if I input 2 numbers, 3 and 1, the answer would be -2, which is obviously incorrect. Division is also not functioning properly.
I can input 2 numbers, 8 and 4, and it would tell me the answer is 0.5, which is also incorrect.
What went wrong in my code?
print("Welcome to 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 would you like to use?: "))
x = int(input("How many numbers would you like to use?: "))
if operations == 1:
a = 0
sum = 0
while a < x:
number = int(input("Please enter number here: "))
a += 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)
回答1:
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. Then it goes through again with 4 as number
and 8 as quo
. 4 / 8
= .5
Here's an alternative solution using reduce
from the 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 like to know why this was downvoted when it is indeed the answer why division wasn't working...
回答2:
Issue is with these lines..
diff = 0
while s < x:
number = int(input("Please enter number here: "))
s += 1
diff = calculator.subtraction(number,diff)
print("The answer is", diff)
Lets say input is 2 line number 3 of the above snippet, The difference in the first iteration of the loop, number (input) is 2 and diff is already 0
- 2-0 = 2 diff becomes 2 now Input is 1 in the second iteration,
- 1 -2 = -1 number is 1 and 1 - diff will become diff. that is -1.
Since in the loop you mentioned, (number,diff) - subtraction happens in the same order
来源:https://stackoverflow.com/questions/45383183/wrong-results-for-calculator-subtraction-and-division