C++實現將十進位數轉換為小於等於九的任意進位,十進位進位

來源:互聯網
上載者:User

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);
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.