将一个十进制数转换成八进制数。 #include<iostream> using namespace std; #define OK 1 #define ERROR 0 #define OVERFLOW -2 typedef int Status; typedef struct SNode { int data; struct SNode *next; } SNode, *LinkStack; Status InitStack(LinkStack &S) { S = NULL; return OK; } bool StackEmpty(LinkStack S) { if (!S) return true; return false; } Status Push(LinkStack &S, int e) { LinkStack p; p = new SNode; if (!p) { return OVERFLOW; } p->data = e; p->next = S; S = p; return OK; } Status Pop(LinkStack &S, int &e) { LinkStack p; if (!S) return ERROR; e = S->data; p = S; S = S->next; delete p; return OK; } void conversion(int N) { int e; LinkStack S; InitStack(S); while (N) { ; N = N / 8; } while (!StackEmpty(S)) { ; cout << e; } } int main() { int n, e; cin >> n; conversion(n); return 0; }
时间: 2024-02-14 20:07:38 浏览: 155
这段代码存在一些问题,主要是在 conversion 函数中的两个 while 循环没有完整的实现转换十进制到八进制的逻辑,导致计算结果错误。下面是修改后的代码:
```
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct SNode {
int data;
struct SNode *next;
} SNode, *LinkStack;
Status InitStack(LinkStack &S) {
S = NULL;
return OK;
}
bool StackEmpty(LinkStack S) {
if (!S)
return true;
return false;
}
Status Push(LinkStack &S, int e) {
LinkStack p;
p = new SNode;
if (!p) {
return OVERFLOW;
}
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S, int &e) {
LinkStack p;
if (!S)
return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
void conversion(int N) {
int e;
LinkStack S;
InitStack(S);
while (N) {
Push(S, N % 8);
N = N / 8;
}
while (!StackEmpty(S)) {
Pop(S, e);
cout << e;
}
}
int main() {
int n;
cin >> n;
conversion(n);
return 0;
}
```
修改后的代码可以正确的将一个十进制数转换成八进制数。
阅读全文