今天惡補彙編,發現腦殼變遲鈍了,因此寫了個小程序,練習一下二進制轉換,鞏固記憶~~ios
先來看看二進制(Binary)、十進制(Decimal)、十六進制(Hexadecimal)的關係表格git
Decimal (base 10) |
Binary (base 2) |
Hexadecimal (base 16) |
0 | 0000 | 0 |
1 | 0001 | 1 |
2 | 0010 | 2 |
3 | 0011 | 3 |
4 | 0100 | 4 |
5 | 0101 | 5 |
6 | 0110 | 6 |
7 | 0111 | 7 |
8 | 1000 | 8 |
9 | 1001 | 9 |
10 | 1010 | A |
11 | 1011 | B |
12 | 1100 | C |
13 | 1101 | D |
14 | 1110 | E |
15 | 1111 | F |
根據對應關係,寫了以下小代碼,亦能夠統計成功率小程序
1 #include <iostream> 2 #include <ctime> 3 #include <cstdlib> 4 #include <string> 5 #include <bitset> 6 #include <iomanip> 7 8 using namespace std; 9 10 int main(int argc, char *argv[]) 11 { 12 cout << "You must enter a 4-digit binary number." << endl; 13 cout << "If you enter 'q' or 'Q', then the game over~"<< endl; 14 cout << "Now, let's start the game!" << endl; 15 cout << endl; 16 17 unsigned long correctCount = 0; 18 unsigned long totalCount = 0; 19 srand(time(NULL)); 20 do{ 21 unsigned long v = rand() % 16; 22 if(0 == (rand() - (v >> 1)) % 2){ 23 cout << "0x" << hex << uppercase << v << " = " << resetiosflags(ios_base::hex | ios_base::uppercase); 24 }else{ 25 cout << v << " = "; 26 } 27 28 string str; 29 cin >> str; 30 31 if(0 == str.compare("q") || 0 == str.compare("Q")){ 32 cout << endl; 33 break; 34 } 35 36 if(str.size() > 4){ 37 cout << "Please enter a valid 4-digit binary number" << endl; 38 }else{ 39 try{ 40 bitset<4> foo(str); 41 42 totalCount++; 43 if(foo.to_ulong() == v){ 44 correctCount++; 45 cout << "^_-! Bingo!" << endl; 46 }else 47 cout << "-_-! Once again!" << endl; 48 }catch(...){ 49 cout << "Please enter the binary format!" << endl; 50 } 51 } 52 53 cout << endl; 54 }while(1); 55 56 if(totalCount > 0) 57 cout << "Correct Rate: " << correctCount / double(totalCount) * 100 << "%" << endl; 58 59 cout << "Bye-bye ^_^!" << endl; 60 return 0; 61 }