how to check sqrt of number is integer c++
To check if the square root of a number is an integer in C++, you can use the sqrt
function from the cmath
library. Here are the steps to do this:
- Include the
cmath
library at the beginning of your code to access thesqrt
function.
#include <cmath>
- Declare a variable to store the number for which you want to check the square root.
int number = 16;
- Use the
sqrt
function to calculate the square root of the number.
double squareRoot = sqrt(number);
- Check if the square root is an integer by comparing it to its rounded value. You can use the
round
function from thecmath
library to round the square root.
if (squareRoot == round(squareRoot)) {
// The square root is an integer
// Perform your desired operations here
} else {
// The square root is not an integer
// Perform other operations here
}
- You can repeat this process for different numbers by assigning new values to the
number
variable and executing the steps above.
Here's the complete code:
#include <iostream>
#include <cmath>
int main() {
int number = 16;
double squareRoot = sqrt(number);
if (squareRoot == round(squareRoot)) {
std::cout << "The square root is an integer." << std::endl;
} else {
std::cout << "The square root is not an integer." << std::endl;
}
return 0;
}
This code checks if the square root of the number 16 is an integer. You can modify the number
variable to check different numbers.