c++ - 打印整个数组而不是子集
问题描述
我使用了 i&(1<<j)!=0 以便在指定 true 或 false 的条件下得到 1 或 0,但我打印的是整个数组而不是子集。虽然我在使用 i&(1<<j) 时得到了正确的结果(给定数组的子集)。
void subsets(int arr[], int n)
{
for(int i=0;i<(1<<n);i++){
for(int j=0; j<n; j++)
{
if(i&(1<<j)!=0)
{
cout<<arr[j]<<" ";
}
}
cout<<endl;
}
}
int main()
{
int arr[3]={1,2,3};
subsets(arr,3);
}
解决方案
clang++
使用和-Werror
标志构建时您的代码编译失败,我们将收到此错误:
operator_precendence.cpp:8:13: error: & has lower precedence than !=; != will be evaluated first [-Werror,-Wparentheses]
if (i & (1 << j) != 0) {
^~~~~~~~~~~~~~~
operator_precendence.cpp:8:13: note: place parentheses around the '!=' expression to silence this warning
if (i & (1 << j) != 0) {
^
( )
operator_precendence.cpp:8:13: note: place parentheses around the & expression to evaluate it first
if (i & (1 << j) != 0) {
^
( )
所以很明显!=
已经先被评估,然后条件检查总是得到true
. 要修复它,我们只需要添加一个括号(编译器已经给了我们提示):
if ((i & (1 << j)) != 0)
或简单地使用if (i & (1 << j))
推荐阅读
- javascript - 从状态数组获取特定值时未定义 - React Native
- css - Button Class 得到的不是 div 的全长?
- c++ - 这是什么''(常量向量
> &A)" 段代码是什么意思? - unity3d - Unity3d:如何从 HTTP 接收输入
- java - 即使从服务器删除后,数据仍显示在房间数据库中
- django - 使用 django-secretballot 和 intercooler.js 制作 ajax 按钮
- mysql - MySQL 在搜索“する”时返回“ずる”(日语)
- kubernetes - 在将 pod 调度到节点时,k8s 是否考虑“请求”或“限制”资源?
- jquery - Bootstrap carousel 仅适用于 jquery slim 但需要完整的 jquery
- android - 如何在 RecyclerView 上显示插入 Sqlite 数据库的日期