通過例子進階學習C++(八)進制轉換

本文是通過例子學習C++的第八篇,通過這個例子可以掌握進制之間的轉換。

1.問題描述

在日常生活中,使用十進制進行數學運算,每個數位上的數字只能是0~9,不同位上對應的數值的權重是不同的,如數字123,個位的3代表3,十位上的數字2代表20,百位上的1代表100。

在計算機中使用二進制,每個數位上的數字只能是0~1,不同位上的數字代表的權重不同,如數字(1011)2,其中中各位1代表十進制的1,十位1代表2,千位上的1代表8,依此類推……

以此類推,常用的還有8進制,16進制;

其中16進制,每個數位上的數字只能是0~7,如(111)8。個位上的1表示1,十位上的1表示8,千位上的1表示64,依此類推……

其中16進制,每個數位上的數字只能是0~9,A、B、C、D、E、F,如(111)16。個位上的1表示1,十位上的1表示16,千位上的1表示256,依此類推……

本文將介紹各種數值之間的轉換。

2.二進制和十進制之間的轉換

二進制轉十進制,方法是按權展開。

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

int main(){
	cout<<"請輸入一個二進制數:";
	char s[100];
	long num=0;
	long index = 1;
	gets(s);
	for(int t=strlen(s)-1;t>=0;t--){
		//cout<<s[t]<<"--";
		num += (s[t]-'0') * index;
		index = index * 2;
	}
	
	cout<<num;
	return 0;
}

程序運行效果如下:

十進制轉二進制,方法是除2取餘,倒過來即可。

#include<iostream>
#include<stack>
using namespace std;

int main(){
	stack<int> s;
	int n;
	cout<<"請輸入一個10進制數:"; 
	cin>>n;
	while(n){
		s.push(n%2);
		n /= 2;
	}
	while(! s.empty()){
		cout<<s.top();
		s.pop();
	}
	return 0;
}

程序運行效果如下:

3.十進制和十六進制的轉換

下面以十進制轉十六進制的兩種實現方法,和十進制轉二進制類似,採用除16取餘,倒過來即可。

3.1 通過stack和if語句實現

#include<iostream>
#include<stack>
using namespace std;
int main(){
	stack<int>s;
	int n;
	cin>>n;
	while(n>0)
	{
		s.push(n%16);
		n /= 16;
	}   
	while(!s.empty()){
		//cout<<s.top();
		if(s.top()==10) cout<<'A';
		else if(s.top()==11) cout<<'B';
		else if(s.top()==12) cout<<'C';
		else if(s.top()==13) cout<<'D';
		else if(s.top()==14) cout<<'E';
		else if(s.top()==15) cout<<'F';
		else cout<<s.top();
		s.pop();
	}
	
	return 0;
}

3.2 通過stack和switch語句實現

#include<iostream>
#include<stack>
using namespace std;
int main(){
	stack<int>s;
	int n;
	cout<<"請輸入一個十進制數:";
	cin>>n;
	while(n>0)
	{
		s.push(n%16);
		n /= 16;
	}   
	while(!s.empty()){
		//cout<<s.top();
		switch(s.top()){
			case 10:
				cout<<'A';
				break;
			case 11:
				cout<<'B';
				break;
			case 12:
				cout<<'C';
				break;
			case 13:
				cout<<'D';
				break;
			case 14:
				cout<<'E';
				break;
			case 15:
				cout<<'F';
				break;
			default:
				cout<<s.top();
		}
		s.pop();
	}
	
	return 0;
}

程序運行效果如下:

4.總結

本着Talk is cheap. Show me the code原則,代碼實現不做過多解釋。

本文從構思到完成,可謂是耗費了大量的心血。

如果您閱讀本文後哪怕有一丟丟收穫,請不要吝嗇你手中關注點贊的權力,謝謝!

另外,如果需要相關代碼,請留言,可以提供完整源代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章