首页 > 代码库 > 二进制练习小游戏
二进制练习小游戏
今天恶补汇编,发下脑袋变迟钝了,所以写了个小程序,练习一下二进制转换,巩固记忆~~
先来看看二进制(Binary)、十进制(Decimal)、十六进制(Binary)的关系表格
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 7 using namespace std; 8 9 int main(int argc, char *argv[]) 10 { 11 cout << "You must enter a 4-digit binary number." << endl; 12 cout << "If you enter ‘q‘ or ‘Q‘, then the game over~"<< endl; 13 cout << "Now, let‘s start the game!" << endl; 14 cout << endl; 15 16 unsigned long correctCount = 0; 17 unsigned long totalCount = 0; 18 srand(time(NULL)); 19 do{ 20 unsigned long v = rand() % 16; 21 if(0 == (rand() - (v << 1)) % 2) 22 cout << hex << uppercase << v << " = "; 23 else 24 cout << v << " = "; 25 26 string str; 27 cin >> str; 28 29 if(0 == str.compare("q") || 0 == str.compare("Q")){ 30 cout << endl; 31 break; 32 } 33 34 if(str.size() > 4){ 35 cout << "Please enter a valid 4-digit binary number" << endl; 36 }else{ 37 try{ 38 bitset<4> foo(str); 39 40 totalCount++; 41 if(foo.to_ulong() == v){ 42 correctCount++; 43 cout << "^_-! Bingo!" << endl; 44 }else 45 cout << "-_-! Once again!" << endl; 46 }catch(...){ 47 cout << "Please enter the binary format!" << endl; 48 } 49 } 50 51 cout << endl; 52 }while(1); 53 54 if(totalCount > 0) 55 cout << "Correct Rate: " << correctCount / double(totalCount) * 100 << "%" << endl; 56 57 cout << "Bye-bye ^_^!" << endl; 58 return 0; 59 }
二进制练习小游戏
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。