C++ program to enter any number and calculate its square root
ADVERTISEMENTS
C++ program to enter any number and calculate its square root.
There are you will learn how to find the square root of any number in the C++ language.
Formula:
r = n^(1/2)
where:
r = root
n = number
There are two ways to implement these formulae:
- By using the sqrt() function
- Second, by using the pow() function
Note: before using sqrt() & pow() function you have to include cmath library in the program.
1. By using the sqrt() function
// C++ program to calculate the square root of a number
#include <iostream>
#include <cmath>
// to import the sqrt() function
using namespace std;
int main() {
double n, r;
// n = number
// r = root
cout << "Enter any number to find the square root::\n";
cin >> n;
/* Calculate square root of number */
r = sqrt(n);
// Output
cout << "Square root of " << n << " = " << r;
return 0;
}
Output:
Enter any number to find the square root::
25
Square root of 25 = 5
2. By using the pow() function
// C++ program to calculate the square root of a number using the pow() function
#include <iostream>
#include <cmath>
// to import the pow() function
using namespace std;
int main() {
double n, r;
// n = number
// r = root
cout << "Enter any number to find the square root::\n";
cin >> n;
/* Calculate square root of number */
r = pow(n, 0.5);
// Output
cout << "Square root of " << n << " = " << r;
return 0;
}
Output:
Enter any number to find the square root::
25
Square root of 25 = 5