首页 > 代码库 > C++各种进制的转换

C++各种进制的转换

 

 1 /* 2 @author:CodingMengmeng 3 @theme:各种进制之间的转换 4 @time:2017-1-6 21:39:08 5 @blog:http://www.cnblogs.com/codingmengmeng/ 6 */ 7 #include <iostream> 8 using namespace std; 9 10 //十进制数转换成二进制数11 void decimal2Binary(int n)12 {13     if (n < 2)14         cout << n;15     if (n >= 2)16     {17         decimal2Binary(n / 2);18         cout << n % 2;19     }20 }21 22 //十进制数转换成八进制数23 void decimal2Octal(int n)24 {25     if (n < 8)26         cout << n;27     if (n >= 8)28     {29         decimal2Octal(n / 8);30         cout << n % 8;31     }32 }33 34 //十进制转换成十六进制数35 void decimal2Hex2(int n)36 {37     switch (n)38     {39         case 10:    cout << "A"; break;40         case 11:    cout << "B"; break;41         case 12:    cout << "C"; break;42         case 13:    cout << "D"; break;43         case 14:    cout << "E"; break;44         case 15:    cout << "F"; break;45         default:cout << n;46     }47 }48 49 void decimal2Hex(int n)50 {51     if (n < 16)52         decimal2Hex2(n);53     if (n>16)54     {55         decimal2Hex(n / 16);56         decimal2Hex2(n % 16);57     }58 }59 60 int main(void)61 {62     int n;63     cout << "input a value of n :" << endl;64     cin >> n;65     cout << "the results that decimal converts to binary,octal and Hex are as follows:" << endl;66     decimal2Binary(n);67     cout << endl;68     decimal2Octal(n);69     cout << endl;70     decimal2Hex(n);71     cout << endl;72 73     getchar();74     return 0;75 }

运行结果:

技术分享

 

C++各种进制的转换