+ -
当前位置:首页 → 问答吧 → 用栈实现二进制转十进制时遇到错误

用栈实现二进制转十进制时遇到错误

时间: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

为什么少输出了四个呢?????

作者: 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()有些问题吧。所以结果才不对???大家给看看

作者: LanerGaming   发布时间: 2011-12-12

热门下载

更多