c++ - 数字后面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;
}
解决方案
您的代码中最令人惊讶的是:
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
在没有真正意义的地方使用。最好简单地删除它。
推荐阅读
- python - 基于特定开始和结束事件的 Pyspark 拆分会话
- javascript - 我目前正在尝试创建一个 chrome 扩展(带有右键搜索的 ContextMenu)
- python - 并排绘制多个混淆矩阵
- sql-server - 如果有使用该用户运行的 SSIS 包,我从 Active Directory 重置 SQL Server 密码会发生什么
- javascript - JS - 满足条件时将对象从数组复制到新数组[编辑]
- firebase - Firestore,检查 valueChanges() 期间更改了哪些字段
- css - CSS:如何将一个 div 移到另一个上方?
- ios - 更新后无法打开 Realm Studio - Realm 文件当前在另一个进程中打开 - Mac 和 Realm Swift
- performance - 有效地循环子阵列
- c++ - libwebsockets:待处理的消息