根据十进制转换成其他进制的计算方法:不断用十进制与R相除,然后取余数,最后再把整个结果颠倒过来,设计的程序如下:
#include
#include
#include
using namespace std;
string Convert(int num, int R)
{
string res;
vectortemp;
int remainder = 0;
while (num != 0)
{
remainder = num % R;
num = num / R;
temp.push_back(remainder);
}
vector::reverse_iterator iter;
for (iter = temp.rbegin(); iter != temp.rend(); iter++)
{
if (*iter >= 10)
res.push_back((char)(*iter - 10) + 'A');
else
res.push_back(*iter + '0');
}
return res;
}
int main()
{
int num, R;
string res;
cout << "输入要转换的数字:" << endl;
cin >> num;
cout << "输入要转换的进制:" << endl;
cin >> R;
res = Convert(num, R);
cout << "输出的" << R << "进制结果为:" << endl;
cout << res << endl;
return 0;
}
结果如图:
程序在附件中
不复杂,是一个常见的练习题目,建议你先写出转二进制的代码
然后再修改成R进制
char chi[100];
char *changeit(long x,int H,char *dd)
{
char HH[]="0123456789ABCDEF";
char nchi[100];
char *stri=nchi;
int i,j;
if (x==0){
*stri='0';
stri++;
}
while(x!=0){
i=x%H;
x=x/H;
*stri=HH[i];
stri++;
}
*stri=0;
for(j=0,i=strlen(nchi)-1;i>=0;i--,j++){
dd[j]=nchi[i];
}
return(dd);
}
void main()
{
printf("%s\n",changeit(97,16,chi)); /*把97转换成16进制*/
getch();
}