利用栈实现输入十进制得到十六进制的c++代码
时间: 2023-06-02 10:04:01 浏览: 53
好的,下面是用栈实现输入十进制得到十六进制的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DIGITS 100
typedef struct {
int data[MAX_DIGITS];
int top;
} Stack;
void push(Stack *s, int num) {
if (s->top == MAX_DIGITS - 1) {
printf("Error: stack overflow\n");
exit(1);
}
s->data[++(s->top)] = num;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Error: stack underflow\n");
exit(1);
}
return s->data[(s->top)--];
}
int main() {
int n, rem, i;
char str[MAX_DIGITS];
Stack s;
s.top = -1;
printf("Enter a decimal number: ");
scanf("%d", &n);
while (n != 0) {
rem = n % 16;
push(&s, rem);
n /= 16;
}
printf("The hexadecimal representation is: ");
while (s.top != -1) {
i = pop(&s);
if (i < 10) {
sprintf(str, "%d", i);
} else {
switch (i) {
case 10:
strcpy(str, "A");
break;
case 11:
strcpy(str, "B");
break;
case 12:
strcpy(str, "C");
break;
case 13:
strcpy(str, "D");
break;
case 14:
strcpy(str, "E");
break;
case 15:
strcpy(str, "F");
break;
}
}
printf("%s", str);
}
return 0;
}
```