【问题标题】:Having trouble with string to float in python字符串在python中浮动时遇到问题
【发布时间】:2012-04-15 05:06:40
【问题描述】:

我的目标是创建一个将度数转换为弧度的程序。公式是 (degrees * 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'

从此代码:

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

main()

编辑:谢谢大家的帮助!

【问题讨论】:

    标签: python string error-handling floating-point


    【解决方案1】:
    float(degrees) 
    

    什么都不做。或者,更确切地说,它从字符串输入度数中生成一个浮点数,但不会将它放在任何地方,因此度数仍然是一个字符串。这就是 TypeError 的意思:您要求它将字符串乘以数字 3.14。

    degrees = float(degrees)
    

    会做的。

    顺便说一句,数学模块中已经有在角度和弧度之间转换的函数:

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

    【讨论】:

    • 我只想补充一点,字符串在 python 中是不可变的,因此对它们的所有操作都会创建一个新对象,从不修改原始对象。
    • 谢谢!!是的,我知道,但是我的老师希望我自己为此创建一个函数。
    【解决方案2】:

    float() 不修改它的参数,它以float 的形式返回它。我怀疑你想要的是(也出于习惯添加标准__name__ 约定):

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

    【讨论】:

    猜你喜欢
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2011-06-05
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    相关资源
    最近更新 更多