【发布时间】:2017-11-18 03:44:31
【问题描述】:
我需要一个用于整数的pow 版本。我有 2 个问题需要通过 pow 解决:
- 如果结果大于我的整数类型,我需要钳位到
numeric_limits::max() - 我需要能够处理 41.99999 向上取整到 42,而不是向下取整到 41
C++ 是否在这里为我提供了某种内联解决方案,还是我一直在编写自己的函数:
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 是的......如果有办法保证 1 和 2 不会被违反。有没有办法做到这一点?
-
您可以使用尾递归和一些数字技巧来提高运行时性能。此外,您可以将此方法设为 constexpr。 stackoverflow.com/questions/9348933/…
标签: c++ floating-point integer pow clamp