数据结构用顺序栈将10进制数转换成任意进制


/*1)利用顺序栈实现将10进制数转换为x进制数,2<=x<=36,除了阿拉伯数字字符,
不够字符使用大写英文字符。要求键盘输入10进制数和转换的目标进制数。
比如:37转换为20进制数为1H。
第一组数据:4
第二组数据:311
第三组数据:7254
第四组数据:98357
*/
#include
#include
using namespace std;
#define max 100
typedef int element;
typedef struct sStack {
    element data[max];
    int top;
}seqStack;
void initialStack(seqStack &S) {
    S.top = -1;
}
bool stackEmpty(seqStack& S) {
    if (S.top == -1)
        return true;
    else
        return false;
}
bool stackFull(seqStack& S) {
    if (S.top == max - 1)
        return true;
    else
        return false;
}
bool pushStack(seqStack& S, element x) {
    if (stackFull(S))
        return false;
    else
    {
        S.data[S.top] = x;
        S.top++;
        return true;
    }
}
bool popStack(seqStack& S,element x) {
    if (stackEmpty(S))
        return true;
    else {
        x = S.data[S.top];
        S.top--;
        return true;
    }
}
void switchStack(seqStack& S) {
    int x; 
    int n;
    cout << "输入10进制数:";
    cin >> x;
    cout << "输入转换的目标进制数:";
    cin >> n;
    int mod,y=0;
     while (x != 0 ) {
        mod = x % n;
        if (mod < 10) {//如果余数是10以内,直接用数字表示
            pushStack(S, mod);
        }
        else {
            int i = mod - 9;
            char j = 'A' + i;
            pushStack(S, j);
        }
         x = x / n;
     }
    cout << "转换后的数为:"<< endl;
    while (!stackEmpty(S))
    {
        popStack(S, y);
        cout << y;
    }

}
int main() {
    seqStack S;
    initialStack(S);
      switchStack(S);
    return 0;
}

想问一下,代码哪里有问题,编译没错,输完要转换的10进制数和要转换成的进制后,就崩了,也不知道是什么错误

img

img

以下代码有问题,initstack后top是-1,那么你应该先top++,否则写入s.data[-1],越界了。

bool pushStack(seqStack& S, element x) {
    if (stackFull(S))
        return false;
    else
    {
        S.data[S.top] = x;
        S.top++;
        return true;
    }
}