# 顺序栈的进制转换，直接操作对象.pop()出现错误

• 147

``````#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");
}

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();
}
}

1 个回答
✓ 已被采纳

``````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;
}``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进