YouTip LogoYouTip

C Function Cos

# C Library Function - cos() [![Image 3: C Standard Library - ](#) C Standard Library - ](#) ## Description The C library function **double cos(double x)** returns the cosine of the angle **x** (in radians). `cos()` is a function in the C standard library `` used to calculate the cosine of an angle (in radians). This function is very commonly used in trigonometric calculations involved in mathematical computations, physical simulations, and engineering applications. ## Declaration Below is the declaration for the cos() function. #include double cos(double x);float cosf(float x);long double cosl(long double x); ## Parameters * `x`: The angle in radians, of type `double`, `float`, or `long double`. ## Return Value Returns the cosine of `x`, in the range [-1, 1]. ## Example The following example demonstrates the usage of the cos() function. ## Example #include #include #define PI 3.14159265 int main () { double x, ret, val; x =60.0; val = PI /180.0; ret =cos( x*val ); printf("The cosine of %lf degrees is %lfn", x, ret); x =90.0; val = PI /180.0; ret =cos( x*val ); printf("The cosine of %lf degrees is %lfn", x, ret); return(0); } Let us compile and run the above program, this will produce the following result: The cosine of 60.000000 degrees is 0.500000 The cosine of 90.000000 degrees is 0.000000 ### Calculating Cosine for Different Angles The following example shows how to calculate the cosine of multiple angles: ## Example #include #include int main(){ double angles[]={0, M_PI /6, M_PI /4, M_PI /3, M_PI /2, M_PI}; const char* angle_labels[]={"0","Ο€/6","Ο€/4","Ο€/3","Ο€/2","Ο€"}; int num_angles =sizeof(angles)/sizeof(angles); for(int i =0; i < num_angles; i++){ double angle = angles; double result =cos(angle); printf("cos(%s) = %fn", angle_labels, result); } return 0; } Code Explanation: * Define an array `angles` containing multiple angles, each in radians. * Define a corresponding label array `angle_labels` for printing output. * Use a `for` loop to iterate through each angle, calculate its cosine, and print the result. Let us compile and run the above program, this will produce the following result: cos(0) = 1.000000 cos(Ο€/6) = 0.866025 cos(Ο€/4) = 0.707107 cos(Ο€/3) = 0.500000 cos(Ο€/2) = 0.000000 cos(Ο€) = -1.000000 ### Error Handling The `cos()` function is valid for all real inputs, so no special error handling is required. The function does not set `errno` and does not return NaN, unless the input itself is NaN or infinity. In such cases, the returned result will be NaN. ### Summary The `cos()` function is used to calculate the cosine of a given angle (in radians) and is an important tool for handling trigonometric operations. By using the `cos()` function appropriately, accurate results can be obtained in mathematical computations, physical simulations, and engineering applications. [![Image 4: C Standard Library - ](#) C Standard Library - ](#)
← C Function SqrtC Function Tolower β†’