二进制练习小游戏

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

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

 

Decimal
(base 10)
Binary
(base 2)
Hexadecimal
(base 16)
000000
100011
200102
300113
401004
501015
601106
701117
810008
910019
101010A
111011B
121100C
131101D
141110E
151111F

  根据对应关系,写了如下小代码,亦可以统计成功率

  

 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 }

 

转载于:https://www.cnblogs.com/Code-Killer/p/7203541.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值