你的代码没有编译,你应该尽可能先检查你的代码编译,使用你的编译器,或者先在编译器资源管理器上检查它。
此外,你忘了考虑负值。这是整体力量的一个非常重要的特征。下面的代码是针对普通的int类型的。我会让你探索一下如何将它扩展到其他整型。
#include <type_traits>
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
template <typename T>
enable_if_t< is_integral<T>::value, T>
mypow(T base, unsigned int exp)
{
T result = T(1);
bool sign = (base < 0);
if (sign) base = -base;
T temp = result;
while(exp-- != 0)
{
temp *= base;
if (temp < result)
{
return (sign) ? numeric_limits<T>::min()
: numeric_limits<T>::max();
}
result = temp;
}
return (sign && (exp & 1)) ? -result : result;
}
template <typename T>
enable_if_t< !is_integral<T>::value, int>
mypow(const T& base, unsigned int exp)
{
T result = T(1);
int i_base = int(floor(base + .5));
bool sign = (i_base < 0);
if (sign) i_base = -i_base;
int temp = result;
while(exp-- != 0)
{
temp *= i_base;
if (temp < result)
{
return (sign) ? numeric_limits<int>::min() : numeric_limits<int>::max();
}
result = temp;
}
return (sign && (exp & 1)) ? -result : result;
}
在现实生活中,我会做这样的使用注意事项地板,即使是在整体情况。
template<typename T>
enable_if_t< is_integral<T>::value, T>
mypow(T x, unsigned int y) { return T(floor(pow(x, y) + .5)); }
template<typename T>
enable_if_t< !is_integral<T>::value, int>
mypow(T x, unsigned int y) { return int(floor(pow(floor(x + .5), y) + .5)); }
你不能使用['std :: pow'](http://en.cppreference.com/w/cpp/numeric/math/pow)并截断结果,如果需要? – NathanOliver
@NathanOliver是啊...如果有一种方法可以保证** 1 **和** 2 **不会被违反。有没有办法做到这一点? –
您可以使用尾递归和某些数字欺骗来提高运行时性能。此外,你可以使这个方法constexpr。 https://stackoverflow.com/questions/9348933/using-recursion-to-raise-a-base-to-its-exponent-c – Andrew