How to use cbrt( ) in C++

The cbrt() function of the cmath library allows you to take the cubic root of any number.

Cubic root is a math function that finds x by following the equation below.

y=x3y = x^{3}

For a given y we can find x by taking y3\sqrt[3]{y}.

The cbrt() function in cmath takes a number of any type in the argument and returns its cubic root. The returned value can be a float, double, long double or int.

Let’s see different examples of how the cbrt() function can be used below.

#include <iostream>
#include <cmath>
using namespace std;
int main() {
// input output both of same type
double x0, y0 = 589.6;
x0 = cbrt(y0);
cout << "Cubic root of " << y0 << " is : " << x0 << endl;
//input output both of different type
double x1;
float y1 = 512;
x1 = cbrt(y1);
cout << "Cubic root of " << y1 << " is : " << x1 << endl;
// output as an integer
// notice that the output will discard any decimal places
int x2;
long double y2 = 56972.3;
x2 = cbrt(y2);
cout << "Cubic root of " << y2 << " is : " << x2 << endl;
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved