c ++中的整数的幂 [英] power of an integer in c++
问题描述
我需要从 pow(a,b)
获得结果作为整数(a和b都是整数)。当前包含(int)pow((double)a,(double)b)
的计算是错误的。也许有人可以帮助一个函数,用pow(a,b)与整数,并返回一个整数吗?
但这里是奇怪的部分:在Linux中使用Geany(和g ++ / gcc编译器)并且只有 pow(a,b)
脚本编译和工作正常。但在大学,我有Dev-C ++(和MS Windows)。在Dev-C ++中,脚本没有编译时出现错误 [Warning]从
/ p> double'转换为
int'
我需要使这个scrpit在Windows下(和Mingw编译器)工作。
/ p>
-skazhy
int myPow(int x,int p){
if(p == 0)return 1;
if(p == 1)return x;
return x * myPow(x,p-1);
}
I need to get the result from pow(a,b)
as an integer (both a and b are integers too). currently the calculations where (int) pow( (double)a, (double)b)
is included are wrong. Maybe someone can help with a function that does the pow(a,b) with integers and returns an integer too?
But here is the odd part: I made my script in Linux with Geany (and g++/gcc compiler) and had just pow(a,b)
the script compiled and worked fine. But in university I have Dev-C++ (and MS Windows). In Dev-C++ the script didn't compile with an error [Warning] converting to
int' from double'
I need to make this scrpit work under Windows (and Mingw compiler) too.
Thanks in advance,
-skazhy
A nice recursive approach you can show off:
int myPow(int x, int p) {
if (p == 0) return 1;
if (p == 1) return x;
return x * myPow(x, p-1);
}
这篇关于c ++中的整数的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!