【问题标题】:problems with integers in the python calculatorpython计算器中的整数问题
【发布时间】:2020-02-29 07:37:15
【问题描述】:

我有 2 个问题。 我的第一个问题是我不知道如何编写整数代码。输出应该写成一个整数......但是当我使用例如 4.3+5 它不起作用......答案应该是“简单” 9...... ValueError:以 10 为底的 int() 的无效文字: 谁能帮我写这个小计算器?

 operation = input('Select an operation (type "addition", 
"subtraction", "multiplication", or "division" and hit enter)')
datatype = input('Select a datatype (type "int" or "float" and hit 
enter)')
value1 = input('Value 1:')
value2 = input('Value 2:')
result = None  # This variable should be overwritten with the result of 
your operation later.


if datatype == "float":
    value1 = float(value1)
    value2 = float(value2)
else:
    value1 = int(value1)
    value2 = int(value2)


if operation == "addition":
    result = value1+value2

elif operation == "subtraction":
    result = value1-value2

elif operation == "multiplication":
    result = value1*value2

elif operation == "division":
    result = value1/value2



print(f"Result: {result}")

这是输出中的一些其他问题 --> 它总是向我显示整个计算...但我只想要解决方案。

输出是:

 Select an operation (type "addition", "subtraction", "multiplication", 
 or "division" and hit enter)multiplication
 Select a datatype (type "int" or "float" and hit enter)float
 Value 1:123456789123456789123456789
 Value 2:-4.3
 123456789123456789123456789 * -4.3 =
 Result: -5.3086419323086415e+26

输出应该是:

    Select an operation (type "addition", "subtraction", 
   "multiplication", or "division" and hit enter)multiplication
    Select a datatype (type "int" or "float" and hit enter)float
    Value 1:123456789123456789123456789
    Value 2:-4.3
    Result: -5.3086419323086415e+26

【问题讨论】:

  • 为什么4.3+5 的答案应该是94.5+5 呢? 4.99999+5?

标签: types numbers integer


【解决方案1】:

它输入方程式的原因,如您所说的“结果:结果”。这导致方程的打印。你可以通过这样做来编辑它:

print("result")

这是我的计算器代码。很短,但可以输入小数。

print("Calculator")

operation = (input("Please choose an operator sign:"))

num1 = float(input("Please put in your first number:"))
num2 = float(input("Please put in your second number:"))

if operation == '+':
  ans = num1 + num2
  print("Your answer is",ans)
elif operation == '-':
  ans = num1 - num2
  print("Your answer is",ans)
elif operation == '*':
  ans = num1 * num2
  print("Your answer is",ans)
elif operation == '/':   
  if num2 == 0:
    print("We cannot divide this number by 0.")
  else:
    ans = num1 / num2
    print("Your answer is",ans)

【讨论】:

  • 我其实还有很多其他类型的计算器,比如幂计算器、闰年计算器、平均分计算器、模数计算器和平方根计算器
  • 如果您需要其中任何一个,请告诉我,我会很高兴向您展示 :)
猜你喜欢
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
相关资源
最近更新 更多