用栈实现二进制转十进制时遇到错误
时间:2011-12-12
来源:互联网
C/C++ code
#ifndef __STACK_H__ #define __STACK_H__ #define MAXSIZE 100 typedef char ElemType; typedef struct{ ElemType *top; ElemType *base; int stackSize; } sqStack; class Stack{ public: Stack(); ~Stack(); void initStack(); void push(ElemType e); ElemType pop(); int stackLongth(); void clearStack(); void destoryStack(); void print(); private: sqStack *items; }; #endif // __STACK_H__ #include "Stack.h" #include <iostream> #include <cmath> using namespace std; Stack::Stack() { this->initStack(); } Stack::~Stack() { this->destoryStack(); } void Stack::initStack() { this->items = new sqStack(); this->items->base = (ElemType *) new ElemType(MAXSIZE); if (!this->items->base) { exit(0); } this->items->top = this->items->base; this->items->stackSize = MAXSIZE; } void Stack::push(ElemType e) { *(this->items->top) = e; ++(this->items->top); } ElemType Stack::pop() { //if (this->items->base == this->items->top) //{ // cout<<"the stack is NULL"<<endl; // exit(0); //} --(this->items->top); return *(this->items->top); } int Stack::stackLongth() { return (this->items->top - this->items->base); } void Stack::clearStack() { this->items->top = this->items->base; } void Stack::destoryStack() { for (int i=0;i!=this->stackLongth();++i) { delete this->items->base; ++(this->items->base); } this->items->base = NULL; this->items->top = NULL; this->items->stackSize = 0; } void Stack::print() { cout<<"show items:"<<endl; for (ElemType *e=this->items->base;e!=this->items->top;++e) { cout<<*e<<endl; } } int main() { Stack *stack = new Stack(); char ch[11] = "1011011001"; for (int i=0;i!=10;++i) { stack->push(ch[i]); } stack->print(); //stack->push('1'); //stack->print(); //cout<<"temp char is:"<<stack->pop()<<endl; //stack->print(); //cout<<"stack longth:"<<stack->stackLongth()<<endl; char c; int sum = 0; for (int i=0;i<=stack->stackLongth();++i) { c = stack->pop(); cout<<"item:"<<c<<endl; sum += (c - 48)*pow(2.0,i); } cout<<"decimail :"<<sum<<endl; getchar(); return 0; }
作者: LanerGaming 发布时间: 2011-12-12
输出结果:
show items
1
0
1
1
0
1
1
0
0
1
item:1
item:0
item:0
item:1
item:1
item:0
为什么少输出了四个呢?????
show items
1
0
1
1
0
1
1
0
0
1
item:1
item:0
item:0
item:1
item:1
item:0
为什么少输出了四个呢?????
作者: LanerGaming 发布时间: 2011-12-12
show items:
1
0
1
1
0
1
1
0
0
1
item:1
item:0
item:0
item:1
item:1
item:0
decimail :25
发现pop()有些问题吧。所以结果才不对???大家给看看
1
0
1
1
0
1
1
0
0
1
item:1
item:0
item:0
item:1
item:1
item:0
decimail :25
发现pop()有些问题吧。所以结果才不对???大家给看看
作者: LanerGaming 发布时间: 2011-12-12
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28