利用顺序栈将一个非负的十进制整数N转换为对应的B进制数。
时间: 2024-02-20 13:58:31 浏览: 15
下面是将一个非负的十进制整数N转换为对应的B进制数的 C 语言代码,利用顺序栈实现:
```
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = item;
}
int pop() {
if (top < 0) {
printf("Stack Underflow\n");
return -1;
}
int item = stack[top];
top--;
return item;
}
void convert(int N, int B) {
while (N > 0) {
int remainder = N % B;
push(remainder);
N = N / B;
}
while (top >= 0) {
printf("%d", pop());
}
}
int main() {
int N, B;
printf("Enter a non-negative decimal integer N: ");
scanf("%d", &N);
printf("Enter the base B (2 <= B <= 16): ");
scanf("%d", &B);
printf("The base-%d representation of %d is: ", B, N);
convert(N, B);
printf("\n");
return 0;
}
```
上述代码中,`convert` 函数利用栈将十进制整数 N 转换为 B 进制数。首先,将 N 对 B 取余数,然后将余数压入栈中,再将 N 除以 B,直到 N 等于 0。最后,弹出栈中的元素,输出 B 进制数。
运行示例:
```
Enter a non-negative decimal integer N: 123
Enter the base B (2 <= B <= 16): 2
The base-2 representation of 123 is: 1111011
Enter a non-negative decimal integer N: 123
Enter the base B (2 <= B <= 16): 8
The base-8 representation of 123 is: 173
Enter a non-negative decimal integer N: 123
Enter the base B (2 <= B <= 16): 16
The base-16 representation of 123 is: 7B
```