我今天刚开始编码,我正试图写一个简单的程序来添加向量。到目前为止
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=1
、VectorAy=6
、VectorBx=3
和{VectorC
应该是[4,8]
,但它显示为[13,62]
。在
input
始终返回字符串对象。如果您希望输入是数字,则需要使用^{演示:
^{pr2}$您需要使用内置的int()函数。在
根据documentation,此函数将“将数字或字符串x转换为整数,如果没有给定参数,则返回0。”
这会将传递给它的输入转换为整数。在
因此,得到的代码应该是:
把你的向量转换成浮点(如果你打算用小数)或整数(如果它们总是简单的整数),然后相加。在
现在他们正在被当作绳子。在
因此
"1"+"3" == "13"
鉴于
int("1") + int("3") == 4
因此:
或者你可以简单地在这里:
^{pr2}$相关问题 更多 >
编程相关推荐