編寫一個算法,將非負的十進制整數轉換為其他進制的數輸出,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);
}

歡迎訪問我的博客https://www.ndmiao.cn/
