【问题标题】:ValueError: invalid literal for int() with base 10: '5.0' [duplicate]ValueError:以 10 为基数的 int() 的无效文字:'5.0' [重复]
【发布时间】:2015-10-16 16:03:45
【问题描述】:

我的代码是

# put your python code here
a=int(input())                   #a for first number
b=int(input())                   #b for second number
op=input()                       #c for operation
if op=='+': print(a+b)
elif op=='-': print(a-b)
elif op=='/':
    if b!=0: print(a/b)
    else: print('Деление на 0!') #'Division by 0!'
elif op=='*': print(a*b)
elif op=='mod': print(a%b)
elif op=='pow': print(a**b)
elif op=='div': print(a//b)

在我的计算机上它运行良好,但我正在尝试学习课程,其中解释器给了我这样的错误:

ValueError: invalid literal for int() with base 10: '5.0'

【问题讨论】:

  • 您使用的是什么版本的 Python? a=int(input()) 并输入“5.0”将适用于 2.7,但不适用于 3.X。

标签: python


【解决方案1】:

您正在尝试将表示为浮点数的字符串转换为 int。这行不通。在 int() 的帮助下指定:

If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal

看下面的例子来帮助说明这一点:

>>> x = int("5.5")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.5'
>>> x = float("5.5")
>>> x
5.5
>>>

在将 int 更改为 float 后使用以下测试输入运行代码,会产生以下结果:

# inputs
5.5
6.6
mod
# output
5.5

【讨论】:

  • 好的。但随后出现了新问题:'ZeroDivisionError: float modulo'
  • 然后在遇到这种情况时使用int(a)int(b)
【解决方案2】:

这是因为您试图将浮点字符串转换为整数。由于您正在尝试创建一个计算器,请使用float() 而不是int()。如果你真的只想要整数使用int(float(input()))

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 2017-12-06
    • 2013-08-04
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多