2 algorothm的cpp幂

时间:2018-11-28 15:17:25

标签: c++ math

所以我希望这段代码能够计算2的次幂,但是直到我在控制台中输入奇数后,它才会停止,我的代码是否有任何修复?在此先多谢了
在此处输入代码:

#include <iostream>
using namespace std;
int main()
{
    int a;
    int counter=0;
    cin >> a;
    while(true){
        cin >> a;
        if(a%2==1)
            break;

            a/=2;
            counter=counter+1;  
    }
    cout << counter;
    return 0;
}

2 个答案:

答案 0 :(得分:4)

您缺少一些东西:

  • 您没有按照需要输入信息。
  • 您的计数程序错误。

Soln:

  • 如果数字n是2的幂,则and的{​​{1}}运算和 n必须为0。在所有其他情况下,结果不是n - 1。说,

    0
  • 使用此技术

    n = 4 (in binary it is 100)
    n - 1 = 3 (in binary it is 11)
    n & (n - 1) = 0
    
      100 (4)
    & 011 (3)
    -----------
      000 (0)
    

答案 1 :(得分:0)

如果要评估所有输入为2的幂,我将使用double作为输入,以使那些指数小于零(0.5、0.25等)。

出于这个目的,由于双精度数是以双精度浮点格式表示的(如IEEE 754-2008标准所定义),因此您只应检查将数字用 std :: frexp (https://en.cppreference.com/w/cpp/numeric/math/frexp)等于0.5:

#include <cmath>

bool isPowerOfTwo(double a)
{
    int exp;
    return std::frexp(a, &exp) == 0.5;
}

然后输入代码:

#include <cmath>
#include <iostream>

bool isPowerOfTwo(double a)
{
    int exp;
    return std::frexp(a, &exp) == 0.5;
}

int main() {
    unsigned counter = 0;

    while (true) {
        double input;
        std::cin >> input;
        if (!isPowerOfTwo(input)) {
            break;
        }
        counter++;
    }
    std::cout << "Number of inputs power of 2: " << counter << std::endl;
    return 0;
}
相关问题