//群:970353786
#include "stdio.h"
#include<iostream>
using namespace std;
#define StackSize 100
typedef char ElemType;
typedef struct
{
ElemType data[StackSize];
int top;
}SqStack;
int trans(int d, int b, char string[]) //string用于存放轉換後的字元串
{
SqStack st;
char ch;
int r, i = 0;
st.top = -1; // 棧初始化
if (b <= 1 || b > 36 || b == 10) // 2≤b≤36且不為10
{
printf_s(" 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]; //将出棧的字元放入字元數組string
st.top--;
}
string[i] = '\0'; //加入字元串結束标志
return 1;
}
void main()
{
while (1)
{
char str[10];
int d, b, t;
printf_s("請輸入整數:"); //請輸入待轉換的整數
scanf_s("%d", &d);
printf("請輸入要轉換為幾進制:"); // 請輸入待轉換的進制
scanf_s("%d", &b);
t = trans(d, b, str); // 調用進制轉換函數
cout << "進制轉換結果為:";
if (t == 0) printf("Error!");
else printf("%s\n", str); // 輸出轉換結果字元串
}
}