用C语言写一个用栈来实现任意进制转换成任意进制的代码程序
时间: 2024-05-12 12:18:04 浏览: 11
好的,以下是用 C 语言写一个用栈来实现任意进制转换成任意进制的代码程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHARS 100
typedef struct {
int top;
char data[MAX_CHARS];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int push(Stack *s, char c) {
if (s->top >= MAX_CHARS - 1) {
return 0;
}
s->top++;
s->data[s->top] = c;
return 1;
}
char pop(Stack *s) {
if (s->top < 0) {
return '\0';
}
char c = s->data[s->top];
s->top--;
return c;
}
char peek(Stack *s) {
if (s->top < 0) {
return '\0';
}
return s->data[s->top];
}
int isEmpty(Stack *s) {
return (s->top < 0);
}
int isDigit(char c) {
return (c >= '0' && c <= '9');
}
int charToInt(char c) {
return (c - '0');
}
char intToChar(int n) {
return (char)(n + '0');
}
int toDecimal(char *num, int base) {
int len = strlen(num);
int res = 0;
int pow = 1;
for (int i = len - 1; i >= 0; i--) {
int digit;
if (isDigit(num[i])) {
digit = charToInt(num[i]);
} else {
digit = num[i] - 'A' + 10;
}
res += digit * pow;
pow *= base;
}
return res;
}
void fromDecimal(int num, int base, char *res) {
Stack s;
initStack(&s);
while (num != 0) {
int rem = num % base;
if (rem < 10) {
push(&s, intToChar(rem));
} else {
push(&s, 'A' + (rem - 10));
}
num /= base;
}
int i = 0;
while (!isEmpty(&s)) {
res[i] = pop(&s);
i++;
}
res[i] = '\0';
}
void convert(char *num, int base1, int base2, char *res) {
int decimal = toDecimal(num, base1);
fromDecimal(decimal, base2, res);
}
int main() {
char num[MAX_CHARS];
int base1, base2;
printf("Enter a number: ");
scanf("%s", num);
printf("Enter the base it is in: ");
scanf("%d", &base1);
printf("Enter the base you want to convert to: ");
scanf("%d", &base2);
char res[MAX_CHARS];
convert(num, base1, base2, res);
printf("%s in base %d converted to base %d is %s\n", num, base1, base2, res);
return 0;
}
```
希望这个代码能够帮到你。如果你还有其它问题,可以直接问我哦!
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)