數制轉換-棧的應用(C++實現)
阿新 • • 發佈:2017-07-11
技術分享 ont while namespace 不同 hit enter rac content
源.cpp
本程序實現的是十進制與不同進制之間的的數據轉換,利用的數據結構是棧,基本數學方法輾轉相除法。
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++實現)