编写一个算法,将非负的十进制整数转换为其他进制的数输出,10及其以上的数字从‘A’开始的字母表示

时间:2023-03-08 18:54:14
编写一个算法,将非负的十进制整数转换为其他进制的数输出,10及其以上的数字从‘A’开始的字母表示

编写一个算法,将非负的十进制整数转换为其他进制的数输出,10及其以上的数字从‘A’开始的字母表示。

要求:

1) 采用顺序栈实现算法;

2)从键盘输入一个十进制的数,输出相应的八进制数和十六进制数。

#include "stdio.h"
#define StackSize 100
typedef char ElemType;
typedef struct
{
ElemType data[StackSize];
int top;
}SqStack;
int trans(int d, int b, char string[])
{
SqStack st;
char ch;
int r, i = 0;
st.top = -1;
if (b <= 1 || b > 36 || b == 10)
{
printf(" b is Error\n");
return 0;
}
while (d!=0)
{
r = d%b;
ch = r + (r < 10 ? '0' : 'A' - 10);
st.top++;
st.data[st.top] = ch;
d /= b;
}
while (st.top != -1)
{
string[i++] = st.data[st.top];
st.top--;
}
string[i] = '\0';
return 1;
}
void main()
{
char str[10];
int d, b, t;
printf("输入一个整数:");
scanf_s("%d", &d);
printf("转换为8进制后的数:\n");
t = trans(d, 8, str);
if (t == 0) printf("Error!");
else printf("%s\n", str);
printf("转换为16进制后的数:\n");
t = trans(d, 16, str);
if (t == 0) printf("Error!");
else printf("%s\n", str);
}

  编写一个算法,将非负的十进制整数转换为其他进制的数输出,10及其以上的数字从‘A’开始的字母表示

欢迎访问我的博客https://www.ndmiao.cn/