猜數字遊戲及相關例題

2021-09-13 13:52:12 字數 2047 閱讀 7285

一、完成猜數字遊戲

在這個**中我用了乙個c語言中很少用到的goto語句;這個語句不被廣泛看好,但是這個語句的語義是可以改變程式流程,直接轉到它所指向的語句,而break僅僅只能跳出當前迴圈,但相對break而言,c語言中goto語句更容易引起程式崩潰,所以很多人不推薦用它,以至於很多人不太明白它的用法。

同時使用了rand()函式和time函式來進行隨機數的呼叫,具體源**如下:

#define  _crt_secure_no_warnings 

#include "stdio.h"

#include "stdlib.h"

#include "time.h"

void main()

if (j == 0)

srand((unsigned)time(0));

int random = rand() % 100;

while (1)

else if (num < random)

else

goto right;

}right :

printf("猜對了");

二、寫**可以在整型有序陣列中查詢想要的數字, 找到了返回下標,找不到返回-1.(折半查詢)

折半查詢的原理大家都知道,這種查詢辦法使許多巨大的篩選工程一次可以消減一半,在實際應用中十分好用,以下為源**:

#define _crt_secure_no_warnings

#include#include #includeint main()

; int k;

int left = arr[0];

int right = sizeof(arr) / sizeof(arr[0]) - 1;

printf("請輸入需要查詢的數:\n");

scanf("%d", &k);

while (left <= right)

else if (arr[mid] <= k)

else

}if (left > right)

system("pause");

return 0;

}

三、編寫**模擬三次密碼輸入的場景。

最多能輸入三次密碼,密碼正確,提示「登入成功」,密碼錯誤,

可以重新輸入,最多輸入三次。三次均錯,則提示退出程式。

#define  _crt_secure_no_warnings 

#include "stdio.h"

#include "stdlib.h"

#include "math.h"

#include "string.h"

void main()

else

printf("密碼錯誤!");

} break;

} printf("登陸成功!");

if (i > 3)

system("pause");

return 0;

}

四、編寫乙個程式,可以一直接收鍵盤字元,

如果是小寫字元就輸出對應的大寫字元,

如果接收的是大寫字元,就輸出對應的小寫字元,

如果是數字不輸出。

#define _crt_secure_no_warnings

#include#include #includeint main()

else if (letter >= 'a'&&letter <= 'z')

else if (letter'z')

}system("pause");

return 0;

}

結束,比心~

例題3 4 猜數字遊戲的提示

寒假回來自己訓練的第一道題,就給懵住了 題目描述 實現乙個經典 猜數字 遊戲。給定答案序列和使用者猜的序列,統計有多少數字位置正確 a 有多少數字在兩個序列都出現過但位置不對 b 輸入輸入包含多組資料。每組輸入第一行為序列長度n,第二行是答案序列,接下來是若干猜測序列。猜測序列全0時該組資料結束。n...

猜數字遊戲

問題描述 猜數字遊戲 隨機出乙個兩位數,然後讓你猜,直到猜對為止。猜對後可以提示選擇是否再玩一次。include include using namespace std int main srand unsigned int time null int num rand 90 10 隨機出乙個兩位數...

猜數字遊戲

author 徐權 data 2015728 function 猜數字遊戲 實用平台 vs2012及以上 如果要移植到其他平台scanf s和puts s 應改為scanf和puts即可 include include include include define n 5 定義陣列大小,從而決定猜的...