Search code examples
c++mingw

Power of an integer in C++


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. What could a function be 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 Microsoft Windows). In Dev-C++, the script didn't compile with an error,

[Warning] converting to 'int' from double'

I need to make this script work under Windows (and the MinGW compiler) too.


Solution

  • 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);
    }