简体   繁体   English

麻烦字符串浮在python中

[英]Having trouble with string to float in python

My goal is to create a program that will convert degrees to radians. 我的目标是创建一个将度数转换为弧度的程序。 The formula is (degrees * 3.14) / 180. But python keeps giving me this error: 公式是(度* 3.14)/180。但是python一直给我这个错误:

Traceback (most recent call last):
  File "2.py", line 6, in <module>
    main()
  File "2.py", line 4, in main
    degrees = (degrees * 3.14) / 180
TypeError: can't multiply sequence by non-int of type 'float'

From this code: 从此代码:

def main():
    degrees = raw_input("Enter your degrees: ")
    float(degrees)
    degrees = (degrees * 3.14) / 180

main()

EDIT: Thank you all for the help! 编辑:谢谢大家的帮助!

float(degrees) 

doesn't do anything. 什么也没做 Or, rather, it makes a float from the string input degrees, but doesn't put it anywhere, so degrees stays a string. 或更确切地说,它使字符串输入度成为浮点数,但没有将其放置在任何地方,因此度数保留为字符串。 That's what the TypeError is saying: you're asking it to multiply a string by the number 3.14. 这就是TypeError的意思:您要让它将字符串乘以数字3.14。

degrees = float(degrees)

would do it. 会做到的。

Incidentally, there are already functions to convert between degrees and radians in the math module: 顺便说一下,数学模块中已经有在度和弧度之间转换的函数:

>>> from math import degrees, radians, pi
>>> radians(45)
0.7853981633974483
>>> degrees(radians(45))
45.0
>>> degrees(pi/2)
90.0

float() doesn't modify its argument, it returns it as a float . float()不会修改其参数,而是将其作为float返回。 I suspect what you want is (also adding standard __name__ convention out of habit): 我怀疑您想要什么(出于习惯也添加了标准__name__约定):

def main():
    degrees = raw_input("Enter your degrees: ")
    degrees = float(degrees)
    degrees = (degrees * 3.14) / 180

if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM