acos() Function Example in C Programming

In this source code example, we will see how to use the acos() function in C programming with an example.

acos() Function Overview

The acos() function in C is utilized to calculate the arccosine (or inverse cosine) of a specified value. The resulting angle is in radians and lies within the range \([0, π]\). 

The acos() function resides in the math.h library. The function takes one argument: the value whose arccosine is to be computed, which must be within the interval [-1, 1]. 

Key Points: 

- Ensure to include the math.h header to access the acos() function. 

- The argument provided to the function must be between -1 and 1, both inclusive. 

- The function returns the result in radians. If required, this can be converted to degrees using the equation: degree = radian × 180 / π

- During compilation, it's essential to link the math library using the -lm flag.

Source Code Example

#include <stdio.h>
#include <math.h>  // Required for acos()

int main() {
    double value, result_in_radians, result_in_degrees;

    // Prompt user for value whose arccosine needs to be computed
    printf("Enter a value between -1 and 1: ");
    scanf("%lf", &value);

    // Validate that the input is within the permissible range
    if (value < -1 || value > 1) {
        printf("Error: The input value must be in the range [-1, 1].\n");
        return 1;
    }

    // Determine the arccosine of the value
    result_in_radians = acos(value);

    // Convert the result into degrees for a more familiar representation
    result_in_degrees = result_in_radians * 180.0 / M_PI;

    // Showcase the results
    printf("Arccosine of %.2lf in radians is: %.2lf\n", value, result_in_radians);
    printf("Arccosine of %.2lf in degrees is: %.2lf\n", value, result_in_degrees);

    return 0;
}

Output

Enter a value between -1 and 1: 0.5
Arccosine of 0.50 in radians is: 1.05
Arccosine of 0.50 in degrees is: 60.00

Explanation

1. We initiate by including the necessary header files: stdio.h for I/O operations and math.h to access the acos() function.

2. Within the main() function, we solicit a value from the user for which the arccosine needs to be determined.

3. A check is performed to ensure the input value resides within the interval [-1, 1]. If it doesn't, an error message is relayed, and the program terminates.

4. Using the acos() function, we compute the arccosine of the provided value.

5. Additionally, we translate the result into degrees for clarity.

6. Both the radian and degree values are then displayed on the console.


Comments