gpt4 book ai didi

python - 整数乘以分数和小数时Python程序出错

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:29 25 4
gpt4 key购买 nike

我试图编写一个简短的程序来计算著名的德雷克方程。我让它接受整数输入、小数输入和小数输入。但是,当程序尝试将它们相乘时出现此错误(在我输入所有必要的值后立即发生错误):

Traceback (most recent call last)
File "C:/Users/Family/Desktop/Programming/Python Files/1/DrakeEquation1.py", line 24, in <module>
calc() #cal calc to execute it
File "C:/Users/Family/Desktop/Programming/Python Files/1/DrakeEquation1.py", line 17, in calc
calc = r*fp*ne*fl*fi*fc*l
TypeError: can't multiply sequence by non-int of type 'str'

我的代码如下:

def intro():
print('This program will evaluate the Drake equation with your values')

def calc():
print('What is the average rate of star formation in the galaxy?')
r = input()
print('What fraction the stars have planets?')
fp = input()
ne = int(input('What is the average number of life supporting planets (per star)?'))
print('What fraction of these panets actually develop life')
fl = input()
print('What fraction of them will develop intelligent life')
fi = input()
print('What fraction of these civilizations have developed detectable technology?')
fc = input()
l = int(input('How long will these civilizations release detectable signals?'))
calc = r*fp*ne*fl*fi*fc*l

print('My estimate of the number of detectable civilizations is ' + calc + ' .')


if __name__=="__main__":
intro() #cal intro to execute it
calc() #cal calc to execute it

我需要更改什么才能解决此问题?

最佳答案

您需要将输入值转换为 float 。

r = float(input())

(注意:在低于 3 的 Python 版本中,使用 raw_input 而不是 input。)

其他变量依此类推。否则,您将尝试用一个字符串乘以一个字符串。

编辑:正如其他人指出的那样,calc 也不能使用 + 运算符连接到周围的字符串。为此使用字符串替换:

print('My estimate of the number of detectable civilizations is %s.' % calc)

关于python - 整数乘以分数和小数时Python程序出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11698341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com