十进制转任意进制

十进制转任意进制采用取余倒排法

#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

//转换函数
//输入:要转换的数, 转换后的进制
string translate(int num, unsigned int base)
{
    if(base == 0)
    {
        cout << "进制不能为0" << endl;
    }

    string ret;

    while(num)
    {
        ret.push_back('0' + num % base);
        num /= base;
    }
    //STL泛型算法,反转
    reverse(ret.begin(), ret.end());
    return ret;
}

int main(int argc, char** argv)
{
    if(argc != 3)
    {
        cout << "usage: ./a.out <num> <base>" << endl;
    }

    int num, base;
    sscanf(argv[1], "%d", &num);
    sscanf(argv[2], "%d", &base);
    string str = translate(num, base);
    cout << str << endl;
    return 0;
}
    原文作者:进制转换
    原文地址: https://blog.csdn.net/shanghairuoxiao/article/details/75579180
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞