数制变换-栈的应用(C++实现)

数制转换-栈的应用(C++实现)

本程序实现的是十进制与不同进制之间的的数据转换,利用的数据结构是栈,基本数学方法辗转相除法。

conversion.h

#include<stack>
using namespace std;
//将十进制的数据n转换成m进制的数据
stack<int> conversion(unsigned int n,unsigned int m)
{
	stack<int> s;
	while(n)
	{
		s.push(n%m);
		n = n/m;
	}
	return s;
}

源.cpp

#include<iostream>
#include<stack>
#include"conversion.h"
using namespace std;
int main()
{
	int n = 1348;
	//将n转换成8进制
	stack<int> s = conversion(n,8);
	while(!s.empty())
	{
		cout<<s.top();
		s.pop();
	}
	cout<<endl;
	//将n转换成2进制
	s = conversion(n,2);
	while(!s.empty())
	{
		cout<<s.top();
		s.pop();
	}
	cout<<endl;
}

数制变换-栈的应用(C++实现)