关于bitset的一个小问题

snsn1984
博客专家认证
2008-10-29 10:07:05
#include<iostream>
#include<bitset>

using namespace std;

int main()
{
bitset<32> bits;
int x=1,y=0,z=0;
while(z<=21)
{
bits.set(z);
y=x;
x=z;
z=x+y;

}
cout<<"bits: "<<bits<<endl;
return 0;
}
我这样的话,调试运行都正常,但是下边的方法调试没有错误,运行报错.
#include<iostream>
#include<bitset>

using namespace std;

int main()
{
bitset<32> bits;
int x=1,y=0,z=0;
while(z<=21)
{

y=x;
x=z;
z=x+y;
bits.set(z);
}
cout<<"bits: "<<bits<<endl;
return 0;
}
运行报的错误信息:Debug Error!
请教为什么会出现这样的情况?顺序不同为什么会导致完全不同的两种情况?先谢谢大家.
...全文
168 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
snsn1984 2008-10-29
  • 打赏
  • 举报
回复
这个分,分的不太均匀,感谢每个兄弟,希望大家别介意哦.
snsn1984 2008-10-29
  • 打赏
  • 举报
回复
谢谢大家,我把2)中的z<=21改成了21,就可以正常执行了.
太乙 2008-10-29
  • 打赏
  • 举报
回复


#include <iostream>
#include <bitset>

using namespace std;

int main()
{
bitset <32> bits;
int x=1,y=0,z=0;
while(z <=21)
{

y=x;
x=z;
z=x+y;
bits.set(z);
}
cout <<"bits: " <<bits <<endl;
return 0;
}



因为z==21后,进入while循环,z=34,而对于bits.set(34)肯定会报错

而如果把bits.set(z)放在开头,那么z就不会出现=34的情况!!

z = 34 是因为z=x+y引起的@






帅得不敢出门 2008-10-29
  • 打赏
  • 举报
回复
看输出最清楚了.

#include <iostream>
#include <bitset>

using namespace std;

int main()
{
bitset <32> bits;
int x=1,y=0,z=0;
while(z <=21)
{

y=x;
x=z;
z=x+y;
cout << "Z" << z << endl;
bits.set(z);
cout << "bits: " <<bits <<endl;
}

return 0;
}

Z1
bits: 00000000000000000000000000000010
Z1
bits: 00000000000000000000000000000010
Z2
bits: 00000000000000000000000000000110
Z3
bits: 00000000000000000000000000001110
Z5
bits: 00000000000000000000000000101110
Z8
bits: 00000000000000000000000100101110
Z13
bits: 00000000000000000010000100101110
Z21
bits: 00000000001000000010000100101110
Z34
Press any key to continue
Jncryang 2008-10-29
  • 打赏
  • 举报
回复
第二个程序是Z运行完结果后在赋值,执行最后一次循环时,Z值经x+Y计算后得34,超过了32最大值,因此出错!
sys0004 2008-10-29
  • 打赏
  • 举报
回复
bitset <32> bits; 设置了最大位数为32
因为1)中你的while(z<=21)保证了z不会大于32,所以没问题
2)中因为在while(z<=21)做了y=x;x=z;z=x+y;导致最后一次z的值大于32越界所以出错了。
bitxinhai 2008-10-29
  • 打赏
  • 举报
回复
y=x;
x=z;
z=x+y;
bits.set(z);//当z>32时,bitset会出现运行时错误!!应该首先判断z是否大于32
fox000002 2008-10-29
  • 打赏
  • 举报
回复
差别就是,后者在执行到 z=34 的时候继续执行 bits.set(z); 这就报错,来不及判断 z <=21

前者执行到 z=34 后,判断 z <=21 就退出了

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧