Python 计算器减法和除法的错误结果
我的加法和乘法都很好。然而,对于减法,如果我输入2个数字,3和1,答案将是-2,这显然是不正确的。该司也没有正常运作 我可以输入2个数字,8和4,它会告诉我答案是0.5,这也是不正确的 我的代码出了什么问题Python 计算器减法和除法的错误结果,python,python-3.x,calculator,Python,Python 3.x,Calculator,我的加法和乘法都很好。然而,对于减法,如果我输入2个数字,3和1,答案将是-2,这显然是不正确的。该司也没有正常运作 我可以输入2个数字,8和4,它会告诉我答案是0.5,这也是不正确的 我的代码出了什么问题 print("Welcome to Calculator!") class Calculator: def addition(self,x,y): added = x + y return added def subtraction(self
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)
print(“欢迎使用计算器!”)
类计算器:
def添加(自身、x、y):
添加=x+y
返回添加
def减法(自、x、y):
减去=x-y
减去返回值
def乘法(自、x、y):
乘以=x*y
回报倍增
def分区(自身、x、y):
除以=x/y
收益分配
计算器=计算器()
打印(“1\t添加”)
打印(“2\t提取”)
打印(“3\t倍增”)
打印(“4\tVision”)
operations=int(输入(“您希望使用什么操作:”)
x=int(输入(“您希望使用多少个数字?”:”)
如果操作==1:
a=0
总和=0
而a
我想知道为什么这是被否决的原因,而这确实是为什么部门不工作的答案…问题在于这些行
diff = 0
while s < x:
number = int(input("Please enter number here: "))
s += 1
diff = calculator.subtraction(number,diff)
print("The answer is", diff)
diff=0
当s
假设输入是上面代码段的第3行中的2,循环的第一次迭代中的差异,数字(输入)是2,而diff已经是0
因为在你提到的循环中,(数字,差异)-减法是以相同的顺序发生的在“控制面板的事情”中,用其他变量改变变量,比如这个
other\u diff=calculator。减法(数字,差异)
你在计算相同的数字,就像你在做一些奇怪的递归,并考虑使用更多括号,因为您正在使用Python 3xSuffy!这有助于解决减法的问题,但是除法呢?您发送的数字和差值作为参数的顺序是错误的,对于division Nevermind也是一样。除法和减法都不是关联运算。加法和乘法是相同的。除法也是相同的情况。使用functools中的reduce确实是解决这个问题的好方法。我会投你一票。没有人能否决这个答案。谢谢@KathiravanNatarajan。我不想让它听起来像是我在乞求选票。我只是糊涂了。
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)
diff = 0
while s < x:
number = int(input("Please enter number here: "))
s += 1
diff = calculator.subtraction(number,diff)
print("The answer is", diff)