计算给定角度的余弦,舍入结果并打印

Calculate cosine of given angle, round result and print it

这似乎是一个简单的练习,但即使阅读了文档,我也坚持了几个小时。它具有以下 description.

需要使用给定模板作为起点:

# import the required library

def calculate_cosine(angle_in_degrees):
    # do not forget to round the result and print it
    ...

输入样本由培训网站自行提供。所以我的尝试是这样的:

#import the required library
import math

def calculate_cosine(angle_in_degrees):
# do not forget to round the result and print it
    math.cos(angle_in_degrees)
    print(round(angle_in_degrees, 2))

这段代码有什么问题?度量单位应该是半径?

非常感谢对此的任何帮助!

math.cos takes the angle in radians, not degrees. So you need to convert from degrees to radians yourself. How? Just another bit of math: Conversion between radians and degrees (Wikipedia)

是的,角度应该以弧度为单位。

如果您不知道如何转换它,只需将角度乘以 pi 再除以 180。

这个函数应该可以完成工作

def calc_cos(angleindeg):
    x=math.cos((math.pi*angleindeg)/180)
    return round(x,2)