如何使输入成为数值

2024-09-23 06:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天刚开始编码,我正试图写一个简单的程序来添加向量。到目前为止

VectorAx= input("What is the x component of Vector A?")
VectorAy= input("What is the y component of Vector A?")
VectorBx= input("What is the x component of Vector B?")
VectorBy= input("What is the y component of Vector B?")


VectorC= "[%s,%s]" % (VectorAx + VectorBx, VectorAy+VectorBy)
print (VectorC)

当我运行脚本时,一切正常,但输入不被当作数字处理。 例如,如果VectorAx=1VectorAy=6VectorBx=3和{},VectorC应该是[4,8],但它显示为[13,62]。在


Tags: ofthe程序编码inputiswhatcomponent
3条回答

input始终返回字符串对象。如果您希望输入是数字,则需要使用^{}^{}将其转换为数字:

VectorAx= int(input("What is the x component of Vector A?"))
VectorAy= int(input("What is the y component of Vector A?"))
VectorBx= int(input("What is the x component of Vector B?"))
VectorBy= int(input("What is the y component of Vector B?"))

演示:

^{pr2}$

您需要使用内置的int()函数。在

根据documentation,此函数将“将数字或字符串x转换为整数,如果没有给定参数,则返回0。”

这会将传递给它的输入转换为整数。在

因此,得到的代码应该是:

VectorAx = int(input("What is the x component of Vector A?"))
VectorAy = int(input("What is the y component of Vector A?"))
VectorBx = int(input("What is the x component of Vector B?"))
VectorBy = int(input("What is the y component of Vector B?"))

把你的向量转换成浮点(如果你打算用小数)或整数(如果它们总是简单的整数),然后相加。在

现在他们正在被当作绳子。在

因此"1"+"3" == "13"

鉴于int("1") + int("3") == 4

因此:

VectorAx= int(input("What is the x component of Vector A?"))
VectorAy= int(input("What is the y component of Vector A?"))
VectorBx= int(input("What is the x component of Vector B?"))
VectorBy= int(input("What is the y component of Vector B?"))


VectorC= "[%s,%s]" % (VectorAx + VectorBx, VectorAy+VectorBy)

或者你可以简单地在这里:

^{pr2}$

相关问题 更多 >