本文章為大家介紹一個(gè)非常有趣的游戲, 猜數(shù)字序苏,能鍛煉思維邏輯哦蚕苇,十分推薦K缮辍2永铩关炼!
-
功能概述
1.隨機(jī)產(chǎn)生1~9的四個(gè)不重復(fù)數(shù)字
2.將產(chǎn)生的四個(gè)數(shù)從小到大排序
3.接收用戶輸入四個(gè)數(shù)
4. 如果位置正確且數(shù)字正確用A輸出
如果數(shù)字正確位置不正確用B輸出
例:
產(chǎn)生的隨機(jī)數(shù): 1 3 5 8
玩家輸入: 1 5 6 8
提示結(jié)果: 2A1B
-
技術(shù)實(shí)現(xiàn)
1.產(chǎn)生四個(gè)不同的隨機(jī)數(shù)
//產(chǎn)生四個(gè)隨機(jī)數(shù)
srand((unsigned)time(NULL));
int a[4] = {0};
for (int i = 0; i < 4; i++) {
bool isExisting = false;
int temp = rand() % 9 + 1;
for (int j = 0; j < i; j++) {
if (temp == a[j]) {
i--;
isExisting = true;
break;
}
}
if (isExisting == false) {
a[i] = temp;
//printf("%d ",a[i]);
}
}
此過程用到了rand()函數(shù),只需要導(dǎo)入頭文件<stdlib.h>匣吊。
注意:產(chǎn)生隨機(jī)數(shù)需要播種(seed)儒拂,即調(diào)用一次srand(),這個(gè)函數(shù)是給隨機(jī)數(shù)產(chǎn)生一個(gè)隨機(jī)種子(seed)色鸳,函數(shù)原型是srand( (unsigned) time(NULL));time的值每時(shí)每刻都不同社痛。所以種子不同,所以命雀,產(chǎn)生的隨機(jī)數(shù)也不同蒜哀。種子只需要播一次就夠了,如果將srand也寫入循環(huán)吏砂,會導(dǎo)致產(chǎn)生的隨機(jī)數(shù)相同撵儿。
2.為產(chǎn)生的隨機(jī)數(shù)排序
//排序
for (int i = 0; i < 4; i++) {
for (int j = 1 + i; j < 4; j++) {
int k = 0;
if (a[i] > a[j]) {
k = a[i];
a[i] = a[j];
a[j] = k;
}
}
}
3.接收用戶輸入并判定結(jié)果
//接收用戶輸入
int b[4] = {};
printf("請輸入您猜的四個(gè)數(shù)字:");
scanf("%d%d%d%d",&b[0],&b[1],&b[2],&b[3]);
//記錄
int allRight = 0, halfRight = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (b[i] == a[j]) {
if (i == j) {
allRight++;
}else{
halfRight++;
}
}
}
}
printf("%dA%dB\n",allRight,halfRight);
4.總代碼
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
//產(chǎn)生四個(gè)隨機(jī)數(shù)
srand((unsigned)time(NULL));
int a[4] = {0};
for (int i = 0; i < 4; i++) {
bool isExisting = false;
int temp = rand() % 9 + 1;
for (int j = 0; j < i; j++) {
if (temp == a[j]) {
i--;
isExisting = true;
break;
}
}
if (isExisting == false) {
a[i] = temp;
//printf("%d ",a[i]);
}
}
printf("\n");
//排序
for (int i = 0; i < 4; i++) {
for (int j = 1 + i; j < 4; j++) {
int k = 0;
if (a[i] > a[j]) {
k = a[i];
a[i] = a[j];
a[j] = k;
}
}
}
int wrongTime = 0;
while (1) {
//接收用戶輸入
int b[4] = {};
printf("請輸入您猜的四個(gè)數(shù)字:");
scanf("%d%d%d%d",&b[0],&b[1],&b[2],&b[3]);
//記錄
int allRight = 0, halfRight = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (b[i] == a[j]) {
if (i == j) {
allRight++;
}else{
halfRight++;
}
}
}
}
printf("%dA%dB\n",allRight,halfRight);
if (allRight != 4) {
wrongTime++;
if (wrongTime >= 4) {
printf("錯(cuò)誤四次乘客,您失敗了!\n");
break;
}
printf("您猜錯(cuò)了淀歇,還剩余%d次機(jī)會\n",4-wrongTime);
}else{
printf("恭喜您成功了\n");
break;
}
}
return 0;
}
-
效果展示
a.gif
-
總結(jié)感悟
今天寫代碼感覺挺順的易核,一路寫下來,但運(yùn)行起來就悲劇了浪默,再加上下午腦袋有點(diǎn)糊牡直,調(diào)試了半天才把bug修復(fù)。我覺著現(xiàn)在的我浴鸿,還是寫一步先運(yùn)行看看結(jié)果井氢,這樣應(yīng)該不會浪費(fèi)太多時(shí)間。