开发者

Ambiguous pow() function

I am trying to make a simple call to the pow() function from math.h someihing similar to..

#include<math.h>
int main()
{
    float v,w;
    w=3.0;
    v=pow(w,0.5);//i think this is 'float pow(float,float)'
    return 0;
}

but visual studio says it's an error

1>c:\users\user\documents\visual studio 2008\projects\deo\deo\main.cpp(7) : error C2666: 'pow' : 6 overloads have similar conversions
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(575): could be 'long double pow(long double,int)'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(573): or       'long double pow(long double,long double)'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(527): or       'float pow(float,int)'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(525): or       'float pow(float,float)'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\math.h(489): or       'double pow(double,int)'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\开发者_如何转开发include\math.h(123): or       'double pow(double,double)'
1>        while trying to match the argument list '(float, double)'

I thought I had the format float pow(float, float).


In the line:

v=pow(w,0.5);

w is a float and 0.5 is a double. You can use 0.5f instead.


Math functions like pow(), sin() etc are templatized in more modern C++ implementations. The reason it is ambiguous is that it is unclear what you want to do. If you send in both arguments being the same, you presumably want the computation to be done at that specific precision. If they are different, then do you want to compute at the higher precision and upcast the lower precision operand, or do you want to downcast the higher precision to lower precision and then do the computation at lower precision. i.e.

float a,b;
double c,d;
pow(a,b); // not ambiguous, done at float precision
pow(c,d); // not ambiguous, done at double precision
pow(a,c); // ambiguous, gives error
pow((double)a,c); // not ambiguous, performs computation at double precision
pow(a,(float)c); // not ambiguous, gives computation at float precision, but c might lose precision in the down cast


Try v=pow(w,0.5f);


0.5 is of type double. Try

v=pow(w,0.5f);


Hey, have you tried 0.5f?


In addition to all other methods that already were given in the other answers, you could always explicitly specify template argument:

float w = 3.0f;
double v = 1.5;
v = pow<float>(w, v);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜