数据结构与算法实验--栈(1)

        利用顺序栈或链栈,将一个十进制数n转换为d进制数(d=2~16)并应用,计算十进制487的二进制数、八进制数和十六进制分别是多少?

提示:将十进制数转换为d进制数,可以采用除d取余法。

typedef struct {
	string items[STACKSIZE];
	int top;
}SqStack;
int Push(SqStack* S, string e)  //入栈
{
	if (S->top >= STACKSIZE - 1) {
		printf("堆栈已满,不能完成入栈操作!\n");
		return 0;
	}
	S->top++;
	S->items[S->top] = e;
	return 0;
}
int Pop(SqStack* S, string &e)  //出栈
{
	if (S->top <= -1) {
		printf("堆栈已空,不能完成出栈操作!\n");
		return 0;
	}
	e = S->items[S->top];
	S->top--;
	return 0;
}
int trans(int num, int d, SqStack* S)  //转换
{
	int a;
	string b;
	do 
	{
		a = num % d;   //d进制,除d取余法
		num = (num - a) / d;
		switch (a)     //将余数转换为0,1,…,A,B,C…,将其入栈
		{
		case 0:
			Push(S, "0");
			break;
		case 1:
			Push(S, "1");
			break;
		case 2:
			Push(S, "2");
			break;
		case 3:
			Push(S, "3");
			break;
		case 4:
			Push(S, "4");
			break;
		case 5:
			Push(S, "5");
			break;
		case 6:
			Push(S, "6");
			break;
		case 7:
			Push(S, "7");
			break;
		case 8:
			Push(S, "8");
			break;
		case 9:
			Push(S, "9");
			break;
		case 10:
			Push(S, "A");
			break;
		case 11:
			Push(S, "B");
			break;
		case 12:
			Push(S, "C");
			break;
		case 13:
			Push(S, "D");
			break;
		case 14:
			Push(S, "E");
			break;
		case 15:
			Push(S, "F");
			break;
		}
		
	} while (num != 0);
	while (S->top != -1)   //完成后出栈
	{
		Pop(S, b);
		cout << b << " ";
	}
	return 0;
}
int main()
{
	SqStack shun;
	SqStack* S=&shun;
	S->top = -1;
	cout << "输入十进制数" << endl;
	int num;
	cin>>num;
	cout << "输入转化的进制数" << endl;
	int d;
	cin >> d;
	trans(num, d, S);
	return 0;
}

运行结果:

数据结构与算法实验--栈(1)数据结构与算法实验--栈(1)数据结构与算法实验--栈(1)

上一篇:Java流程控制


下一篇:break注意事项和标签的使用