Having trouble with string to float in python
我的目标是创建一个将度数转换为弧度的程序。公式为(度*3.14)/180。但python一直给我这个错误:
1 2 3 4 5 6 | 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' |
从这个代码:
1 2 3 4 5 6 | def main(): degrees = raw_input("Enter your degrees:") float(degrees) degrees = (degrees * 3.14) / 180 main() |
编辑:谢谢大家的帮助!
1 | float(degrees) |
什么都不做。或者,更确切地说,它从字符串输入度数中创建一个浮点,但不将其放在任何位置,因此度数保持为字符串。这就是typeerror所说的:你要求它将一个字符串乘以数字3.14。
1 | degrees = float(degrees) |
会的。
顺便说一下,数学模块中已经有函数可以在度数和弧度之间进行转换:
1 2 3 4 5 6 7 | >>> from math import degrees, radians, pi >>> radians(45) 0.7853981633974483 >>> degrees(radians(45)) 45.0 >>> degrees(pi/2) 90.0 |
1 2 3 4 5 6 7 | def main(): degrees = raw_input("Enter your degrees:") degrees = float(degrees) degrees = (degrees * 3.14) / 180 if __name__ == '__main__': main() |