顺序栈的进制转换,直接操作对象.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();
    }
}

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

 请问一下这是怎么回事

阅读 3.2k
1 个回答

因为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;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进