sqrt() function

Good day.
I calculate the square root of modulus of two numbers. Modulus operator requires both operands to be int and returns int. At the same time sqrt() is not overloaded to take int as parameter. Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
int * f ( int value )
{
	int Divisor [] = { 2, 3, 13, 17, 19, 29 };
	cout << sizeof (Divisor)/sizeof(Divisor[0]) << endl;
	int * pResult = new int [(sizeof (Divisor)/sizeof(Divisor[0]))*2]; 
	for ( int i = 0, j = 0; i < (sizeof (Divisor)/sizeof(Divisor[0])) * 2; i=i+2, ++j )								// getting the first 7 elemets [0 to 6]
	{	
		pResult [i] = floor( sqrt (value % Divisor [j]) );
		pResult [i+1] = ceil( sqrt (value % Divisor [j]) );
	}
	return pResult;
}


error C2668: 'sqrt' : ambiguous call to overloaded function.
Any suggestions would be appreciated
The sqrt functions take a float or a double or a long double.

http://www.cplusplus.com/reference/clibrary/cmath/sqrt/

You're trying to feed it an int. The compiler doesn't know which sqrt function to use, as it can turn that int into a float, a double or a long double.

Don't feed it an int. Convert that int into something else.
Last edited on
Do you have overloaded sqrt()? That's the only reason why the compiler might find it ambiguous.

BTW, how does the caller of f() know how big the returned array is?
Minor amendment, C++ standard sqrt() functions only take float, double, or long double in pre-2011 C++. Current C++ has integer overloads for std::sqrt() as well.

But yes, based on the diagnostic, your compiler does not support that yet, so cast to double yourself: sqrt ( static_cast<double>(value % Divisor [j]))
I stand corrected. I need to start referring to cppreference.com more. Here it is:

http://en.cppreference.com/w/cpp/numeric/math/sqrt
Last edited on
kbw (4423) Jun 6, 2012 at 8:41pm
Do you have overloaded sqrt()? That's the only reason why the compiler might find it ambiguous.

BTW, how does the caller of f() know how big the returned array is?
Report


No, I have not overloaded sqrt(). I guess the compiler I use is a bit out of date.

I indicated the array size manually. I bet you have a better suggestion kbw :)) If yes, I'm all "eyes".

1
2
3
4
5
6
7
8
9
10
11
12
13
void main ( int argc )
{
	int * result = NULL;
	long value = 0;
	printf_s ( "%s\n", "Please enter number" );
	scanf_s ( "%d", &value );
	result = f ( value );
	for ( int i = 0; i < 12; i=i+2 )
	{
		cout << i <<": "<< result [i] <<"\t"<< i+1 <<": "<< result [i+1] << endl; ;
	}
	system ("PAUSE");
}
Topic archived. No new replies allowed.