用栈进制转换 输出乱码
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include
#define MAXSIZE 2000
#define OVERFLOW -2
#define ERROR 0
#define OK 1
#define Status int
typedef int SELemType;
typedef struct
{
SELemType* base;
SELemType* top;
int stacksize;
}SqStake;
Status InitStack(SqStake* S)
{
S->base = (SELemType*)malloc(MAXSIZE * sizeof(SELemType));
if (!S->base)exit(OVERFLOW);
S->top = S->base;
S->stacksize = MAXSIZE;
return OK;
}
Status Push(SqStake* S, SELemType e) {
if (S->top - S->base == S->stacksize)
return ERROR;
*S->top++ = e;
return OK;
}
Status Pop(SqStake* S, SELemType* e) {
if (S->base == S->top)
return ERROR;
--S->top;
e = *S->top;
return OK;
}
int StackEmpty(SqStake S)
{
if (S.top ==S.base)
{
return 0;
}
else
{
return 1;
};
}
void conversion()
{
SqStake S;
SELemType h;
InitStack(&S);
printf("请输入非负的数:\n");
scanf("%d", &h);
while (h)
{
Push(&S, h % 8);
h = h / 8;
}
SELemType e;
while (StackEmpty(S))
{
Pop(&S, &e);
printf("%d", e);
}
}
void main()
{
conversion();
system("pause");
}
在 Pop 函数中,需要将传入的指针 e 解引用才能将弹出的栈顶元素赋值给它,所以需要修改 Pop 函数的实现,将 e = *S->top; 改为 *e = *(--S->top)。
e = *S->top;
->
*e = *S->top;
这段代码,我看了一下,只需要改一些地方即可,我改好了。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#define MAXSIZE 2000
#define OVERFLOW -2
#define ERROR 0
#define OK 1
#define Status int
typedef int SELemType;
typedef struct
{
SELemType* base;
SELemType* top;
int stacksize;
}SqStake;
Status InitStack(SqStake* S)
{
S->base = (SELemType*)malloc(MAXSIZE * sizeof(SELemType));
if (!S->base)exit(OVERFLOW);
S->top = S->base;
S->stacksize = MAXSIZE;
return OK;
}
Status Push(SqStake* S, SELemType e) {
if (S->top - S->base == S->stacksize)
return ERROR;
*S->top++ = e;
return OK;
}
Status Pop(SqStake* S, SELemType* e) {
if (S->base == S->top)
return ERROR;
--S->top;
*e = *S->top;
return OK;
}
int StackEmpty(SqStake S)
{
if (S.top == S.base)
{
return 1;
}
else
{
return 0;
}
}
void conversion()
{
SqStake S;
SELemType h;
InitStack(&S);
printf("请输入非负的数:\n");
scanf("%d", &h);
while (h)
{
Push(&S, h % 8);
h = h / 8;
}
SELemType e;
while (!StackEmpty(S))
{
Pop(&S, &e);
printf("%d", e);
}
}
int main()
{
conversion();
system("pause");
return 0;
}
下方警告scanf 值被忽略 sacnf 有黄色波浪线
今天学习递归感觉到了一点神奇的东西,有点类似于栈,先进先出或者后进后出。
因为十进制转化为八进制或者二进制都是采用的求余法
以上图为例,因为输出的时候是24,所以必须先输出2在输出4,所以想办法在递归中让最下面的做最底层的函数,这样输出的时候就能从下往上输出了。
#include<stdio.h>
//十进制转八进制
int Translate(int n);
int main()
{
int n;
do{ //循环语句所用到的int型的n,必须定义在循环之前。
printf("请输入整数n:");
scanf("%d",&n);
printf("转化为八进制是:");
Translate(n);
printf("\n");
}while(n!=10);
}
int Translate(int n){
int i,j;
if(n==0)
return 0;
else{
i=n%8;//z求余取结果
j=n/8;//求除数,进行下一级的运算
Translate(j);
printf("%d",i);
}
}