你的代码有一些问题,主要在于弹出和输出元素时出现了错误。以下是修正后的代码:
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
class LinkStack {
public:
struct Node* top;
LinkStack() { top = NULL; }
~LinkStack();
void Push(int x);
int Pop();
bool Empty() { return (NULL == top) ? true : false; }
};
void LinkStack::Push(int x) {
struct Node* p = new Node;
p->data = x;
p->next = top;
top = p;
}
int LinkStack::Pop() {
if (Empty()) throw "下溢";
int x = top->data;
struct Node* p = top;
top = top->next;
delete p;
return x;
}
LinkStack::~LinkStack() {
while (top) {
struct Node* p = top;
top = top->next;
delete p;
}
}
int main()
{
int a, b;
cout << "请输入需要转换的十进制数:";
cin >> a;
cout << "转换后的进制:";
cin >> b;
LinkStack Link;
do {
int x = a % b; // 取余数
a /= b; // 更新被除数
Link.Push(x); // 将余数压入栈中
} while (a != 0);
while (!Link.Empty()) { // 当栈不为空时
int temp = Link.Pop(); // 弹出栈顶元素
if (temp >= 10) {
char ch = (temp - 10) + 'A';
cout << ch;
} else {
cout << temp;
}
}
return 0;
}
修正后的代码中,对于输出字符型数据,使用cout直接输出即可。运行程序后,会根据输入的十进制数和目标进制进行转换,并输出结果。例如,输入十进制数10和目标进制2,则输出结果为”1010”。
内容由零声教学AI助手提供,问题来源于学员提问




