求利用栈把一个10进制数转换城16进制数(c语言)的程序

用c语言写一个十进制转十六进制的程序用栈来实现这个算法
2024-11-12 11:53:09
推荐回答(3个)
回答1:

运行示例:
输入:100000
输出:186a0
程序源码如下:
#include

#include

#define
MAX
100
int
stack[MAX];
int
top
=
0;
int
push(int
*stack,
int
*top,
int
x)
{
if
(*top
==
MAX)
return
0;
stack[(*top)++]
=
x;
return
1;
}
int
pop(int
*stack,
int
*top,
int
*x)
{
if
(*top
==
0)
return
0;
*x
=
stack[--(*top)];
return
1;
}
int
empty(int
*stack,
int
top)
{
return
top
==
0;
}
int
main()
{
unsigned
num
=
0;
scanf("%u",
&num);
while
(num)
{
push(stack,
&top,
num
%
16);
num
/=
16;
}
if
(empty(stack,
top))
push(stack,
&top,
0);
while
(!empty(stack,
top))
{
int
digit
=
0;
pop(stack,
&top,
&digit);
if
(digit
<
10)
printf("%c",
'0'
+
digit);
else
printf("%c",
'a'
+
(digit
-
10));
}
printf("\n");
return
0;
}

回答2:

#include
main()
{
int m;
printf("\nplease input a number:");
scanf("%d",&m); /*输入十进制数字*/
printf("\nthe answer is %x",m);
/*输出十六进制数字*/
}

回答3:

运行示例:
输入:100000
输出:186a0

程序源码如下:
#include
#include

#define MAX 100

int stack[MAX];
int top = 0;

int push(int *stack, int *top, int x)
{
if (*top == MAX)
return 0;
stack[(*top)++] = x;
return 1;
}

int pop(int *stack, int *top, int *x)
{
if (*top == 0)
return 0;
*x = stack[--(*top)];
return 1;
}

int empty(int *stack, int top)
{
return top == 0;
}

int main()
{
unsigned num = 0;
scanf("%u", &num);
while (num)
{
push(stack, &top, num % 16);
num /= 16;
}
if (empty(stack, top))
push(stack, &top, 0);
while (!empty(stack, top))
{
int digit = 0;
pop(stack, &top, &digit);
if (digit < 10)
printf("%c", '0' + digit);
else
printf("%c", 'a' + (digit - 10));
}
printf("\n");
return 0;
}