#include<winuser.inl>
#include<stdio.h>
#include <time.h>
#include <cstdlib>
#include <string.h>
/*
栈的应用实例 -- 数进制转换
要求:输入任意的正整数N(十进制),分别输出该整数的二进制,八进制,十六进制的结果
计算公式: N = (N / d) + N mod d
216(十进制) = 330(八进制) = D8(十六进制) = (11011000)二进制
短除法
(十进制转8进制)
N N /8 N mod 8
216 27 0
27 3 3
3 0 3
(十进制转16进制)
N N /16 N mod 16
216 13 8
13 0 D
16进制里面的数字组成 0~9 A(10) B(11) C(12) D(13) E(14) F(15)
**************************
和栈的关系
先是余数进栈,直到除数为0,最后一个数进栈
然后将所有余数出栈
*/
//坐标栈,二维坐标(x,y)
#define capacity 10
typedef struct tag_stack
{
int *pBuffer;
int top;
int length;
}Stack;
bool InitStack(Stack** pStack)
{
(*pStack) = (Stack*)malloc(sizeof(Stack));
if (*pStack == NULL)
{
printf("Stack failed\n");
return false;
}
else
{
(*pStack)->pBuffer = (int*)malloc(sizeof(int) * capacity);
if ((*pStack)->pBuffer == NULL)
{
printf("(*pStack) -> pBuffer failed\n");
return false;
}
else
{
(*pStack)->top = 0;
(*pStack)->length = 0;
return true;
}
}
}
void DestoryStack(Stack* pStack)
{
free(pStack->pBuffer);
pStack->pBuffer = NULL;
free(pStack);
pStack = NULL;
}
void ClearStack(Stack* pStack)
{
pStack->top = 0;
pStack->length = 0;
}
bool StackEmpty(Stack* pStack)
{
if (pStack->length == 0)
{
printf("stack is empty\n");
return true;
}
else
{
return false;
}
}
bool StackFull(Stack* pStack)
{
if (pStack->length == capacity)
{
printf("stack is full\n");
return true;
}
else
{
return false;
}
}
int StackLength(Stack* pStack)
{
return pStack->length;
}
int Push(Stack* pStack, int *elem ,int N)
{
//elem这里是被除数,也就是上一次短除法的商
if (StackFull(pStack))
{
printf("full\n");
return -1;
}
else
{
int yu_shu,shang;
shang = *elem / N;
yu_shu = *elem % N;
pStack->pBuffer[pStack->top]= yu_shu;
pStack->top++;
pStack->length++;
return shang;
}
}
bool Pop(Stack* pStack, int* elem)
{
if (StackEmpty(pStack))
{
return false;
}
else
{
pStack->top--;
pStack->length--;
*elem = pStack->pBuffer[pStack->top];
return true;
}
}
void Printf(Stack* pStack, bool isFromBottom)
{
if (isFromBottom)
{
for (int i = 0; i <= pStack->length - 1; i++)
{
printf("%d",(pStack->pBuffer)[i]);
}
}
else
{
for (int i = pStack->length - 1; i >= 0; i--)
{
printf("%d", (pStack->pBuffer)[i]);
}
}
printf("\n");
}
int main()
{
Stack* mysatck = NULL;
int number ,N,num1,num2;
printf("请输入你要转换的10进制数:");
scanf_s("%d", &number);
printf("请输入你要将10进制转换成几进制数:");
scanf_s("%d", &N);
num1 = number;
if (InitStack(&mysatck))
{
//printf("the length is:%d \n", StackLength(mysatck));
do
{
num1 = Push(mysatck, &num1, N);
} while (num1 != 0);
printf("the length is:%d \n", StackLength(mysatck));
printf("%d 转换为 %d进制的结果是 :",number,N);
Printf(mysatck, 0);
}
else
{
printf("initial failed\n");
}
return 0;
}
栈实例10进制数转换成2进制,8进制
最新推荐文章于 2023-11-15 22:27:20 发布