C++實現將十進位數轉換為小於等於九的任意進位,十進位進位
//十進位轉換為小於等於九的任意進位數#include<iostream>#include<string>#include<stack>using namespace std;stack<int> num;void change(int N,int M){if(N<0||M<=1){cout<<"error!"<<endl;return;}while(N>0){num.push(N%M);N/=M;}while(!num.empty()){cout<<num.top();num.pop();}cout<<endl;}int main(){for(;;){int N,M;//N代表十進位數,M代表任意機制(小於等於九進位)cout<<"輸入十進位數 進位:";cin>>N>>M;cout<<"轉換為"<<M<<"進位:";change(N,M);}system("pause");return 0;}
3、 C語言實現十進位整數同任意進位的轉換,如10進位轉換為9、6、5、3等進位
直接記住位和權就好了,你看看二進位,八進位那些就知道了
1111b = 1 * 2^3 + 1*2^2 +1*2^1 + 1*2^0 = 15d
其中二進位中2為權,1就位每個數位上的資料
用c語言將任意進位數轉成十進位
任意進位間的轉換
#include <stdio.h>
#include <string.h>
#include <math.h>
/*該函數可以實現小於整型資料的任意進位之間轉換*/
/*以下函數將a進位數s轉換成b進位並輸出*/
void f(int a,int b,char s[])
{ char r[17];
int i,n,t,k;
for(n=strlen(s)-1,i=t=0;*(s+i)!='\0';i++,n--) /*這裡先轉換成十進位數*/
{ if(*(s+i)<='9')
t+=(*(s+i)-'0')*int(pow(a,n));
else
t+=(*(s+i)-'A'+10)*int(pow(a,n));
}
for(i=0;t!=0;i++) /*再轉換成b進位*/
{ k=t%b;
if(k>9)r[i]='A'+k-10;
else r[i]='0'+k;
t/=b;
}
r[i]='\0';
s=strrev(r);
printf("%s",s);
}