In: Computer Science
Using C++
Write a template function that accepts an integer
parameter and returns its integer square root.
The function should return -1, if the argument passed is not
integer.
Demonstrate the function with a suitable driver program .
#include <iostream>
#include<cmath>
using namespace std;
template <class T>
T SquareRoot(T a) {
T result;
result=int(a);
if(result!=a)
return -1;
else
result = sqrt(a);
return result;
}
int main () {
/*
we have make the "n" float type so that we can check
that it is int or not as if we declare it as int then if we enter
any float
or double value then the int type variable will
automatically convert it to int and due to which we can't check
that whether it is int or
any other datatype.
*/
float n;
cout<<"Enter any integer = ";
cin>>n;
int answer;
answer=SquareRoot<float>(n);
cout<<"Square Root of "<<n<<" is
"<<answer;
return 0;
}