数据结构 - 顺序栈的进制转换,直接操作对象.pop()出现错误

查看:136
本文介绍了数据结构 - 顺序栈的进制转换,直接操作对象.pop()出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

用顺序栈写的代码,用来进行进制转换,转换部分都没有错误,在十进制转十六进制的时候,我的思路是先转换成对应数字压到栈里,然后出栈时在输出部分,将大于10的数字转换成字母。但是直接操作对象.pop()时,出现错误。全部代码如下:
头文件:

#include<iostream>
using namespace std;
template<class T>class SeqStack{
private:
    T data[100];
    int top;//栈顶
public:
    SeqStack(){ top = -1; };
    //~SeqStack();
    int push2(T data);
    int push8(T data);
    int push16(T data);
    T pop();//出栈操作
};


template<class T> int SeqStack<T>::push2(T ele){
    int count = 0;
    while (ele != 0){
        top++;
        data[top] = ele % 2;
        ele = ele / 2;
        count++;
    }
    return count;
}
template<class T> int SeqStack<T>::push8(T ele){
    int count = 0;
    while (ele != 0){
        top++;
        data[top] = ele % 8;
        ele = ele / 8;
        count++;
    }
    return count;
}
template<class T> int SeqStack<T>::push16(T ele){
    int count = 0;
    while (ele != 0){
        top++;
        data[top] = ele % 16;
        ele = ele / 16;
        count++;
    }
    return count;
}
template<class T> T SeqStack<T>::pop(){
    if (top == -1) return false;

    return data[top--];
}

主函数:

#include<iostream>
#include"SeqStack.h"
using namespace std;
void main(){
    SeqStack<int> s;
    int num = 0, jinzhi = 0, count;
    int arr[100];
    cout << "请输入一个十进制数:" << endl;
    cin >> num;
    cout << "请输入要转换的进制,例如2,8,16:" << endl;
    cin >> jinzhi;
    if (jinzhi == 2){
        s.push2(num);
        count = s.push2(num);
    }
    if (jinzhi == 8){
        s.push8(num);
        count = s.push8(num);
    }
    if (jinzhi == 16){
        s.push16(num);
        count = s.push16(num);
    }
    cout << "转换结束后对应的进制:" << endl;

    if (jinzhi == 2 || jinzhi == 8){
        for (int i = 1; i <= count; i++){
            cout << s.pop();
        }
    }
    if (jinzhi == 16){
        for (int i = 1; i <= count; i++){
            arr[i] = s.pop();
        }
        for (int i = 1; i <= count; i++){
            if (arr[i] >= 10){
                char x = arr[i] - 10 + 'A';
                cout << x;
            }
            else cout << arr[i];
        }
    }

    cout << endl;
    system("pause");
}


主函数里面的方法是可以输出16进制的,我把它存到数组里面了。
下面这个是直接操作出栈数据的


    if (jinzhi == 16){
    for (int i = 1; i <= count; i++){
        if (s.pop() >= 10){
            char x = s.pop() - 10 + 'A';
            cout << x;
        }
        else cout << s.pop();
    }
}

这个就不行,输出结果就是错误的
错误结果图:

解决方案

因为pop()的用法有误,pop一次,就取一个数,你一次循环怎么能pop多次呢?如下改就好了:

if (jinzhi == 16){
    for (int i = 1; i <= count; i++){
        int tmp = s.pop();
        if (tmp >= 10){
            char x = tmp - 10 + 'A';
            cout << x;
        }
        else cout << tmp;
    }

这篇关于数据结构 - 顺序栈的进制转换,直接操作对象.pop()出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆