C 程序显示数组中的数字(如果是 2 的幂)

标签 c pow

#include <stdio.h>
#include <math.h>

int main(){
    int num,i;
    scanf("%d",&num);

    int a[num];
    for (i=0; i<num; i++){
       scanf("%d",&a[i]);
    }

    for (i=0; i<num+1; i++){
        if (pow(2,i) == a[i]){
            printf("%d\n",a[i]);
        }
    }
}

我正在尝试创建一个程序,显示数组中的整数(如果它是 2 的幂)。前任;数组包含整数 (1,2,4,9),它将仅打印 1,2 和 4。

这段代码有什么问题?它适用于某些测试用例,但不适用于大多数测试用例。

最佳答案

如果是2的幂,则仅设置一位:

#include <stdbool.h>
#include <limits.h>

bool is_pow_of_2(unsigned value)
{
    int count = 0;
    for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift) {
        if (value & 1 << shift)  // test if bit shift is set
            ++count;
        if (count > 1)      // if there a more than one bits set in value
            return false;  //  it cannot be a power of 2
    }

    return true;
}
<小时/>

B计划:

bool is_pow_of_2(signed value)
{
    if(value <= 0)
        return false;

    // ...

关于C 程序显示数组中的数字(如果是 2 的幂),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258482/

相关文章:

c - Sys V ABI 规范(i386 和 AMD64)中描述的标准 "Function Calling Sequence"是否适用于静态 C 函数?

c++ - Matlab Coder 与手动编码?

c - Pthread信号丢失/条件缓慢?

c++ - std::pow() 输出是……特别的?

c++ - 带有两个 mpf_t 的 gmp pow

c - 为什么下面的代码失败

c - 取消索引 Collada

java - 执行具有长指数值的 Math.pow() 操作的最佳方法是什么?

javascript - 将 JavaScript Math.pow 用于 Excel 公式