在C ++中检查数字是否为8的幂
在本节中,我们将看到一个数字是否为8的乘方或不使用某种更简单的方法。如果有4096之类的数字,则程序将返回true,因为这是8的幂。
诀窍很简单。我们将计算log8(num)。如果这是整数,则n是8的幂。在这里,我们将使用tranc(n)函数查找double值的最接近整数。
示例
#include <iostream>
#include <cmath>
using namespace std;
bool isPowerOfEight(int n) {
double val = log(n)/log(8); //get log n to the base 8
return (val - trunc(val) < 0.000001);
}
int main() {
int number = 4096;
if(isPowerOfEight(number)){
cout << number << " is power of 8";
} else {
cout << number << " is not power of 8";
}
}输出结果
4096 is power of 8
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短