我正在尝试自己学习python,通过将简单的数学问题转化为python代码。我遇到了一个简单的循环,如下所示: a3 = (1+a2)/a1。
然后继续练习,如a4 = (1+a3)/a2 Et...我设法输入了输入函数,但似乎在后面的代码中出现了问题,因为python返回了"TypeError:不支持的操作数类型(S) for +:'int‘and 'str'“。
你能帮我弄完吗?!下面是我的代码( a1 = x;a2 = y;a3 = w):
w = 1.
print('give me a number:')
x = input()
print('give me a number:')
y = input()
w = (int((1+y)/x))
print (int(type(w)))非常感谢。我知道这很基本,但我们都是从那些容易犯的错误开始的,不是吗?!(我正试图说服我的大脑,我并不是太愚蠢……:)谢谢
发布于 2021-03-24 04:12:39
你必须把你的输入转换成一个数字,以便在数学中使用它。例如,您可以使用int(string)或float(string)函数来执行此操作。这是必需的,因为输入函数返回一个字符串。
我不确定我是否做对了,但这是我给你的描述:
a1 = float(input("enter a number, hit ctrl+c to exit: "))
a2 = float(input("enter a number, hit ctrl+c to exit: "))
while True:
a3 = (1 + a2) / a1
a1 = a2
a2 = a3
print("a3: %f" % a3)您必须按下ctrl+c才能退出循环。输出:
enter a number, hit ctrl+c to exit: 1234
enter a number, hit ctrl+c to exit: 9876
...
a3: 1234.000000
a3: 9876.000000
a3: 8.004052
a3: 0.000912
a3: 0.125051
a3: 1234.000000
a3: 9876.000000
a3: 8.004052
^Ca3: 0.000912
Traceback (most recent call last):
File "/home/booboo/loopy.py", line 16, in <module>
print("a3: %f" % a3)
KeyboardInterrupthttps://stackoverflow.com/questions/66769874
复制相似问题