用栈实现十进制数转八进制

十进制转换到八进制采用的是除R取余法。将十进制整数除于连续除于R取余数,直到商为0,余数从右到左排列,首次取得的余数排在最右。

将十进制225转换为八进制,答案为341。

代码:

//数组实现的栈
#include<iostream>
#define MaxSize 50
typedef int DataType;
using namespace std;

class stack
{
public:
    stack();
    bool isempty() const;
    bool isfull() const;
    void pop();
    void push(const DataType x);
    DataType get_top();
private:
    int count;
    DataType data[MaxSize];
};

stack::stack()
{
    count = 0;
}

bool stack::isempty() const
{
    if(0==count)
    return true;
    return false;
}

bool stack::isfull() const
{
    if(MaxSize==count)
    return true;
    return false;
}

void stack::pop()
{
    if(isempty())
    cout<<"underflow \n";
    count--;
}

void stack::push(const DataType x)
{
    if(isfull())
    cout<<"overflow \n";
    data[count]=x;
    count++;
}

DataType stack::get_top()
{
    if(isempty())
    cout<<"underflow \n";
    return data[count-1];

//十进制转八进制
int main()
{
    cout<<"请输入一个十进制数:";
    int n;
    cin>>n;
    stack s;
    while(n!=0)
    {
        s.push(n%8);
        n=n/8;
    }
    cout<<"八进制数:"; 
    while(s.isempty()==false)
    {
        cout<<s.get_top();
        s.pop();
    }

运行截图:

猜你喜欢

转载自blog.csdn.net/Drifter_Galaxy/article/details/81459203