cbrt() function in C is a predefined function in the math.h library used to calculate the cube root of a given number. To use this function, we must include the <math.h> header file in our program. It returns the cube root of the number as a double and works with double data types. For other data types like float or long double, we can use cbrtf() and cbrtl() functions, respectively.
Syntax of cbrt() in Cdouble cbrt(double x); Parameters of cbrt()The cbrt(x) function takes a single parameter x:
- x: is a variable of type double whose cube root is to be computed. The value of x can range from negative infinity to positive infinity.
Return Value of cbrt()The cbrt(x) function returns the cube root of the given number x which is passed in the form of radian. The cbrt function supports both negative and positive values so there is no chance for domain errors.
Examples of cbrt() Function in CInput: double x= 27.0
Output: The cube root of 27.0 is 3.000000 Example 1The below program illustrates how to calculate the cube root of a given number using the cbrt(x) function in C.
C++
// C Program to calculate the cube root of a number using
// cbrt() function
#include <math.h>
#include <stdio.h>
int main()
{
// Initialize variable to take the input from the user
// and store the results
double x, cubeRoot;
// Take the input from the user
printf("Enter a number: ");
// Read the number entered by the user
scanf("%lf", &x);
// Calculate the cube root of the entered number
cubeRoot = cbrt(x);
// Print the cube root of the x
printf("The cube root of %.2lf is: %.2lf\n", x,
cubeRoot);
return 0;
}
Output
Enter a number: 27 The cube root of 27.00 is: 3.00 Time Complexity: O(1) Auxiliary Space: O(1)
Example 2The below program illustrates how to find the cube root of different data types in C.
C++
// C program to calculate the cube root of different data
// types in C
#include <math.h>
#include <stdio.h>
int main()
{
// Initialize variables of different data types
double num1 = 27.0;
// float type variable
float num2 = 64.0f;
// long double type variable
long double num3 = 125.0l;
// Calculate the cube root using the appropriate cbrt
// function for each data type
// cbrt function for double
double result1 = cbrt(num1);
// cbrtf function for float
float result2 = cbrtf(num2);
// cbrtl function for long double
long double result3 = cbrtl(num3);
// Print the results
printf("The Cube root of %.2f is %.2f\n", num1,
result1);
printf("The Cube root of %.2f is %.2f\n", num2,
result2);
printf("The Cube root of %.2Lf is %.2Lf\n", num3,
result3);
return 0;
}
OutputThe Cube root of 27.00 is 3.00
The Cube root of 64.00 is 4.00
The Cube root of 125.00 is 5.00
Time Complexity: O(1) Auxiliary Space: O(1)
|