首页 > 解决方案 > 数字后面2的最高幂

问题描述

我正在编写一个代码以在一行中给出数字,输入以零结束,然后将 2 的最高功率小于或等于一行中的输入。它不起作用。

#include<iostream>
#include<stdio.h>

using namespace std;

int highestPowerof2( int n)
{
  static int result = 0;

  for (static int i=n; i>=1; i--)
  {
    if ((i & (i-1)) == 0)
    {
      result = i;
      break;
    }
  }
  return result;
}

int main() {

  static int num ;
  do{
    cin>>num ;
  }
  while(num=!0);

  cout<<highestPowerof2(num)<<"\n";
  return 0;

}

标签: c++

解决方案


您的代码中最令人惊讶的是:

do{
   cin>>num ;
 }
 while(num=!0);

您继续阅读num用户输入,直到num == 0. 我不得不承认我并不真正理解你的其余代码,但num == 0调用函数highestPowerof2(num)总是会导致0.

也许您想重复该程序直到用户决定退出,这可能是

do{
   cin>>num ;
   cout<<highestPowerof2(num)<<"\n";
} while(num=!0);

PS:另一个“令人惊讶”的事情是您static在没有真正意义的地方使用。最好简单地删除它。


推荐阅读