数字进制转换(C++实现)

    xiaoxiao2023-10-11  164

    十进制数N与其他数进制转换原理就是:N=(N div d)xd+N mod d (其中:div为整除运算,mod 为求余运算) 算法为:

    void conversion() { InitStack(S); cin >> N;//要转换的数 cin >> M;//要转换成的进制 while(N) { Push(S, N % M); N = N / M; } while(!StackEmpty(S)) { Pop(S, e); cout << e; } }

    代码如下: (其中stack库用法详见博文C++ 栈函数stack用法)

    #include<iostream> #include<stack> #include<stdlib.h> using namespace std; int main() { stack<int> MyStack; int oldnum, changednum; cout << "please input the number want changed:"; cin >> oldnum; cout << "please iunput the form you want changed:"; cin >> changednum; while(oldnum) { MyStack.push(oldnum % changednum); oldnum = oldnum / changednum; } cout << "the stack size is:"<<MyStack.size(); cout << endl<<"the result is:"; while(!MyStack.empty()) { cout << MyStack.top(); MyStack.pop(); } cout << endl; system("pause"); }

    结果如下

    最新回复(0)