我需要一个针对整数的版本
pow
。我有两个问题需要用pow
解决:
- 如果结果大于我的整数类型,我需要将其夹紧到
numeric_limits :: max()
- 我需要能够处理41.99999四舍五入为42,而不是四舍五入为41
template <typename T>
enable_if_t<is_integral_v<T>, T> mypow(const T base, unsigned int exp) {
T result = exp == 0U ? base : 1;
while(exp-- > 1U) {
if(numeric_limits<T>::max() / result <= base) return numeric_limits<T>::max();
result *= base;
}
return result;
}
std::pow
函数并在必要时截断结果吗? - NathanOliver