#include <iostream>
#include <limits>
#include <cmath>
using namespace std;
int main()
{
int number;
cout << "Enter the number whose sqare root needs to be calculated";
cin >> number;
cout << "Square root of " << number << " is " << (int)sqrt((float)number) << " OR " << sqrt((float)number) << endl;
if( (int)sqrt((float)number) == sqrt((float)number) )
cout << "The number is a perfect sqaure";
else
cout << "The number is not a perfect square";
//To find the nearest perfect square if the number entered
// is not a perfect square?
return 0;
}
I hope what i have done to check the perfect squares is OK, but furthermore I want to
find out the number nearest perfect square if the number entered is not a perfect square
Any Ideas
Actually, here is the better answer:
You don’t need to check between the ceil or the floor of which is greater, doing a simple round does the trick.
sqrt(13) is 3.6 and when you add .5 casts to 4. sqrt(12) is 3.46 and when you add .5 casts to 3. (we’re trying to round, that’s why we add the .5). As you can see, when number is closer to the higher root, it’ll give you a decimal greater than .5; when the number is closer to a lower value root, the decimal is less than .5, simple as that!