计算器减法和除法的结果错误

编程入门 行业动态 更新时间:2024-10-23 04:43:16
本文介绍了计算器减法和除法的结果错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的加法和乘法工作正常。但是,对于减法,如果我输入2个数字3和1,答案将是-2,这显然是错误的。除法也无法正常运行。

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.

我可以输入2个数字8和4,它会告诉我答案是0.5,这也是不正确的。

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)

推荐答案

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)

第一次通过 quo 变为8。然后再次以4作为数字和8作为 quo 。 4/8 = .5

The first time through quo becomes 8. Then it goes through again with 4 as number and 8 as quo. 4 / 8 = .5

这里是另一种选择解决方案使用 functools 库中的 reduce 。

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...

更多推荐

计算器减法和除法的结果错误

本文发布于:2023-10-25 13:44:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527122.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   减法   计算器   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!