利用顺序栈将输入的非负的十进制数N转换为指定的d(二、八或十六)进制数。 顺序栈的定义如下: #define STACKSIZE 100 typedef int DataType; typedef struct { DataType items[STACKSIZE]; /*存放栈中元素的一维数组*/ int top; /*用来存放栈顶元素的下标*/ }SqStack; 函数接口定义: int DecimalConvert(SqStack *s, int dec, int scale);
时间: 2024-03-11 09:51:11 浏览: 178
好的,根据题目要求,我们可以编写如下的 DecimalConvert 函数:
```c
int DecimalConvert(SqStack *s, int dec, int scale) {
// 初始化栈
s->top = -1;
// 如果dec为0,直接入栈0
if (dec == 0) {
Push(s, 0);
}
// 将dec不断除以scale,将余数存入栈中
while (dec > 0) {
Push(s, dec % scale);
dec /= scale;
}
return s->top + 1;
}
```
其中,dec 表示待转换的十进制数,scale 表示目标进制数(二、八或十六),s 表示顺序栈。函数返回值为转换后的进制数的位数。
完整的代码如下:
```c
#include <stdio.h>
#define STACKSIZE 100
typedef int DataType;
typedef struct {
DataType items[STACKSIZE];
int top;
} SqStack;
void InitStack(SqStack *S) {
S->top = -1;
}
int StackEmpty(SqStack *S) {
return S->top == -1;
}
int StackFull(SqStack *S) {
return S->top == STACKSIZE - 1;
}
int Push(SqStack *S, DataType x) {
if (StackFull(S)) {
return 0;
}
S->items[++(S->top)] = x;
return 1;
}
int Pop(SqStack *S, DataType *x) {
if (StackEmpty(S)) {
return 0;
}
*x = S->items[(S->top)--];
return 1;
}
int DecimalConvert(SqStack *s, int dec, int scale) {
// 初始化栈
s->top = -1;
// 如果dec为0,直接入栈0
if (dec == 0) {
Push(s, 0);
}
// 将dec不断除以scale,将余数存入栈中
while (dec > 0) {
Push(s, dec % scale);
dec /= scale;
}
return s->top + 1;
}
int main() {
SqStack s;
int dec, scale;
scanf("%d%d", &dec, &scale);
int len = DecimalConvert(&s, dec, scale);
printf("转换后的%d进制数为:", scale);
while (!StackEmpty(&s)) {
int x;
Pop(&s, &x);
if (x < 10) {
printf("%d", x);
} else {
printf("%c", x - 10 + 'A');
}
}
printf("\n转换后的进制数位数为:%d\n", len);
return 0;
}
```
注意,在输出转换后的进制数时,我们需要将余数转换为对应的进制位。如果余数小于10,直接输出,否则减去10后转换为对应的大写字母。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)