题目要求:
实现M进制到N进制的转换,注意当单个字符超过9时,要使用16进制数表示,例如,将十进制数10转化为16进制数,则表示为A。
解题思路:
首先将M进制转化为10进制,再将10进制转化为N进制,注意超过9数字转换就可以。
实现代码
/*
进制数转换:实现M进制到N进制的转换,输出可表示为16进制
QiYe005 2016.9.16
*/
#include<string>
#include<iostream>
#include<algorithm>
#include<exception>
#include<assert.h>
using namespace std;
/*
练习编写自定义异常并尝试抛
*/
class MyExceptionStringEmpty:std::exception
{
virtual const char* what() const throw()
{
return"输入数组为空!";
}
}myExceptionStringEmpty;
/*
主要参考http://www.cnblogs.com/codingmylife/archive/2011/04/10/2011817.html
总体思路首先实现M进制到10进制的转换,在实现10进制到N进制的转化
*/
void MToNRadix(int&M, string& src, int&N, string *res)
{
assert((M>0)&&(N>0));
if (NULL == src.length())
throw myExceptionStringEmpty;
int decimal=0;
int remain;
for (string::const_iterator constIt = src.begin(); constIt != src.end(); ++constIt)
{
//首先转化为10进制数
decimal = (int)(*constIt-'0')+decimal*M;
}
//尝试转化为N进制数
string returnStr;
if (decimal>=N)
{
while (decimal >= N)
{
remain = decimal%N;
if (remain>=10)
{
returnStr += remain - 10 + 'A';
}
else
{
returnStr += remain + '0';
}
decimal = decimal / N;
}
if (decimal>=10)
{
returnStr += decimal - 10 + 'A';
}
else
{
returnStr += decimal + '0';
}
}
else
{
if (decimal >=10)
{
returnStr = decimal -10 + 'A';
}
else
{
returnStr = decimal + '0';
}
}
reverse(returnStr.begin(), returnStr.end());
*res = returnStr;
}
class MyInputIllegleException :std::exception
{
virtual const char* what() const throw()
{
return "输入数据与输入进制数不合法,请重新检查";
}
}myInputIllegleExcep;
int main(void)
{
try
{
string testStr;
int orgRadix ;
int transRadix ;
cout << "开始测试" << endl;
cout << "请输入原始数字" << endl;
cin >> testStr;
cout << "请输入原始数据进制数" << endl;
cin >> orgRadix;
for (string::iterator it = testStr.begin(); it != testStr.end(); ++it)
{
int singleDig = *it - '0';
if (singleDig >= orgRadix)
{
cout << "输入不合法" << endl;
throw myInputIllegleExcep;
}
}
cout << "请输入待转换进制数" << endl;
cin >> transRadix;
//定义输出结果
string resultStr;
MToNRadix(orgRadix, testStr, transRadix, &resultStr);
cout << "转化结果为" << resultStr << endl;
}
catch (exception ex)
{
cout << ex.what() << endl;
}
}