C++ Program - Cube Root of a Number


Advertisements

If a number is multiplied by itself two times ($$n*n*n$$), the final number will be the cube of that number and inding the cube root of a number is inverse operation of cubing the number. If x is the cube root of y, it can be expressed as below:

$$x = \sqrt[3]{y}$$

Alternatively, it can also be expressed as:

$$x^3 = y$$

Example: Using cbrt() function of C++ <cmath> header file

The cbrt() function of C++ <cmath> header file can be used to return cube root of a number.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
	double x = 64;
	double y = 125;

	double x1 = cbrt(x);
	double y1 = cbrt(y);
	cout<<"Cube root of "<<x<<" is "<<x1<<"\n";
	cout<<"Cube root of "<<y<<" is "<<y1<<"\n";
	return 0;
}

Output

Cube root of 16.0 is 4.0
Cube root of 25.0 is 5.0

Example: Using pow() function of C++ <cmath> header file

The pow() function of C++ <cmath> header file can also be used to calculate cube root of a number.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
	double x = 64;
	double y = 125;

	double x1 = pow(x, 1/3.0);
	double y1 = pow(y, 1/3.0);
	cout<<"Cube root of "<<x<<" is "<<x1<<"\n";
	cout<<"Cube root of "<<y<<" is "<<y1<<"\n";
	return 0;
}

Output

Cube root of 16.0 is 4.0
Cube root of 25.0 is 5.0

Advertisements