码迷,mamicode.com
首页 > 其他好文 > 详细

进制转换

时间:2015-04-15 00:50:26      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

随手写了个进制转换的,低级但也有几点注意的:

#include<iostream>
#include<stack>
#include<sstream>
using namespace std;
stack<char> si;
/*这里采用空间换时间的做法,而且可以扩展成任意想要的表示法*/
char c_arr[36]={‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,
    ‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,
    ‘O‘,‘P‘,‘Q‘,‘R‘,‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘};
string change(int n,const int i){
    /*以下两句是要注意的地方,
       程序应该在输入0时输出也是0
       之前写的是:
       while(n){
           si.push(c_arr[n%i]);
           n=n/i;
       }    测试时发现,在输入0时输出会是空,与期望的效果不符;
       因此在循环之前先做  si.push(c_arr[n%i]);           */
    si.push(c_arr[n%i]);
    while(n=n/i){
        si.push(c_arr[n%i]);
    }

    ostringstream oss;
    for(; !si.empty(); si.pop()){
        oss << si.top();
    }
    string after = oss.str();
    return after;
};

测试:

void test(){
    int before=0,jinzhi=0;
    cout << "input your num:" << endl;
    cin >> before;
    cout << "input jinzhi you‘re to change:" << endl;
    cin >> jinzhi;
    string after = change(before,jinzhi);
    cout << "before:" << before << "   " << "after:" << after << endl;
}
int main(int argc, char**argv){
    test();
}

 

进制转换

标签:

原文地址:http://www.cnblogs.com/young8848/p/4427380.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!