C++ 来自 math.h 库的 pow() - 如何使用函数应用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9344983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pow() from math.h library - How to Apply using functions
提问by Ram Sidharth
So I'm writing a bit of code that needs to raise a function's return value to a certain power. I recently discovered that using the '^' operator for exponentiation is useless because in C++ it is actually an XOR operator or something like that. Now here's the code I want to write:
所以我正在编写一些代码,需要将函数的返回值提高到一定的幂。我最近发现使用 '^' 运算符进行幂运算是没有用的,因为在 C++ 中它实际上是一个 XOR 运算符或类似的东西。现在这是我想写的代码:
int answer = pow(base, raisingTo(power));
Now can anyone tell me if this is right? I'll explain the code. I've declared an int variable answer as you all are aware of, and initialized it to the value of any variable called 'base', raised to the return value of the raisingTo() function acting on any other variable called 'power'. When I do this (and I edit & compile my code in Visual C++ 2010 Express Edition), a red dash appears under the word 'pow' and an error appears saying: "more than one instance of overloaded function 'pow' matches the argument list"
Can someone please solve this problem for me? And could you guys also explain to me how this whole pow() function actually works, cos frankly www.cplusplus.com references are a little confusing as I am still only a beginner!
现在谁能告诉我这是否正确?我会解释代码。正如你们都知道的那样,我已经声明了一个 int 变量答案,并将它初始化为任何名为“base”的变量的值,提升为作用于任何其他名为“power”的变量的 raiseTo() 函数的返回值。当我这样做时(并在 Visual C++ 2010 Express Edition 中编辑和编译我的代码),“pow”这个词下会出现一个红色的破折号,并且出现一条错误消息:“多个重载函数 'pow' 实例与参数匹配list”
有人可以帮我解决这个问题吗?你们能否也向我解释一下整个 pow() 函数实际上是如何工作的,坦率地说,www.cplusplus.com 的引用有点令人困惑,因为我仍然只是一个初学者!
回答by Joey
The documentationstates it pretty explicitly already:
该文件指出它非常明确不已:
The
pow(int, int)
overload is no longer available. If you use this overload, the compiler may emit C2668 [EDIT: That's the error you get]. To avoid this problem, cast the first parameter to double, float, or long double.
该
pow(int, int)
超载不再可用。如果您使用此重载,编译器可能会发出 C2668 [编辑:这是您得到的错误]。为避免此问题,请将第一个参数强制转换为 double、float 或 long double。
Also, to calculate basepoweryou just write
另外,要计算您只需编写的基本功率
pow(base, power)
And with above hint:
并带有上述提示:
int result = (int) pow((double)base, power);
回答by Mike D
The pow() function returns either a double
or a float
, so the first step would be to change answer
to one of those. Second, what is raisingTo()
returning. Unless your are doing something that's not evident, you don't need that, but it should still work. Also, both arguments should be doubles
, according to this.
pow() 函数返回 adouble
或 a float
,因此第一步是更改answer
为其中之一。第二,什么是raisingTo()
回归。除非你正在做一些不明显的事情,否则你不需要它,但它应该仍然有效。此外,doubles
根据this,两个参数都应该是。