I want to consider to code. First it is:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
int s = 25;
cout << sqrt(s) << endl;
return 0;
}
It gave me this mistake:
>c:\users\datuashvili\documents\visual studio 2010\projects\training\training\training.cpp(9): error C2668: 'sqrt' : ambiguous call to overloaded function
1> c:\program files\microsoft visual studio 10.0\vc\include\math.h(589): could be 'long double sqrt(long double)'
1> c:\program files\microsoft visual studio 10.0\vc\include\math.h(541): or 'float sqrt(float)'
1> c:\program files\microsoft visual studio 10.0\vc\include\math.h(127): or 'double sqrt(double)'
1> while trying to match the argument list '(int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
If I add type float in brackets in front of s, like this:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
int s = 25;
cout << sqrt((float)s) << endl;
return 0;
}
I got as I would guess, 5
. And another variant is that instead of sqrt
, if I write sqrtf
:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main(){
int s=25;
cout << sqrtf((float)s) << endl;
return 0;
}
I also got 5
.
What is the difference between them? Does it means that sqrtf is same as sqrt for the float type?
Here's a page on MSDN documentation for sqrt()
and sqrtf()
, that explains the difference:
sqrt, sqrtf
Calculates the square root.
double sqrt( double x ); float sqrt( float x ); // C++ only long double sqrt( long double x ); // C++ only float sqrtf( float x );
Parameters
x: Nonnegative floating-point value
Remarks
C++ allows overloading, so users can call overloads of sqrt that take float or long double types. In a C program, sqrt always takes and returns double.
Return Value
The sqrt function returns the square-root of x. If x is negative, sqrt returns an indefinite, by default.
So the difference in C++ is that sqrt()
accepts either a double
, a float
or a long double
while sqrtf()
accepts only a float
.
As the documentation says, the only reason why there's two different versions is because C did not support overloading, so there had to be two functions. C++ allows overloading, so there are actually three different versions of sqrt()
taking floating point arguments of various sizes.
So in C++, both your code snippets do essentially the same thing. On C, however, there would've been a conversion from float
to double
in the sqrt()
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With