1. 程式人生 > 實用技巧 >十進位制與任意進位制的互相轉換

十進位制與任意進位制的互相轉換

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;

int fact(int n,int p)   //十進位制轉為任意進位制 (n是十進位制數,p是要轉化進位制選擇) 
{
	int res;
	if(n<p)
	return n;
	else
	return n%p+fact(n/p,p)*10;	
}

int inv_fact(int p,int n)   //任意進位制轉為十進位制 
 //p代表當前的數字進位制,n代表當前p進位制下的數字表示 
{
	char s[20];
	int result=0;
	int temp=0;
	sprintf(s,"%d",n);
	int len=strlen(s); //為獲取數字的長度,進行數字轉字串,用strlen求長度 
	//cout<<len<<endl;
	for(int i=0;i<len;i++)
	{
		temp=n%10;
		n=n/10;
		result=result+temp*pow(p,i);
	}
	cout<<result;
	
}

int main()
{
	int m;
	int p;
	cout<<"十進位制轉為任意進位制"<<endl;
	cin>>m>>p;	
	cout<<fact(m,p)<<endl;  
	cout<<"任意進位制轉為十進位制"<<endl;
	cin>>m>>p; 
	inv_fact(m,p);
 }