Search code examples
pythonmathtrigonometrycosine-similarity

Calculate cosine of given angle, round result and print it


It seems like a simple exercise, but I have been stuck on it for some hours even after reading the documentation. It has the following description.

A given template needs to be used a starting point:

# import the required library

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

The input samples are provided by the training website itself. So my attempt went like this:

#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))

What's wrong with this code? The unit of the measure should be in radius?

Really appreciate any help with this!


Solution

  • Yes the angle should be in radians.

    If you don't know how to convert it just multiply the angle by pi and divide by 180.

    This function should do the work

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