二进制练习小游戏

  今天恶补汇编,发现脑袋变迟钝了,所以写了个小程序,练习一下二进制转换,巩固记忆~~

  先来看看二进制(Binary)、十进制(Decimal)、十六进制(Hexadecimal)的关系表格

 

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 }

 

posted @ 2017-07-19 00:11  幻梦雷音  阅读(797)  评论(0编辑  收藏  举报