1. 程式人生 > 程式設計 >C語言實現猜數字小遊戲

C語言實現猜數字小遊戲

本文例項為大家分享了C語言猜數字的具體程式碼,供大家參考,具體內容如下

一、描述

猜數字遊戲。

二、 程式

使用srand((unsigned)time(NULL)),產生隨機數種子。
int random = rand() % 100 + 1,產生0~100之間的隨機數。
應加上標頭檔案#include<time.h>

#include<stdio.h>
#include<windows.h>
#include<time.h>
void menu(){
 printf("#######################\n");
 printf("#    1 Play    #\n");
 printf("#    0 Exit    #\n");
 printf("#######################\n");
}
void Play(){
 int m = 0;
 int random = rand() % 100 + 1;
 while (1)
 {
 printf("請輸入一個數字:\n");
 scanf_s("%d",&m);
 if (m == random){
  printf("你猜對了\n");
  break;
 }
 else if (m > random){
  printf("你猜大了,請重新輸入!");
 }
 else{
  printf("你猜小了,請重新輸入!");
 }
 }
}
 int main()
 {
 srand((unsigned)time(NULL));
 int select = 0;
 do {
 menu();
 printf("請選擇:");
 scanf_s("%d",&select);
 switch (select)
 {
 case 1:
  Play();
  break;
 case 0:
  printf("ByeBye!\n");
  break;
 default:
  printf("輸入錯誤,請重新輸入!\n");
  break;
 }
 } while (select);
 system("pause");
 return 0;
}

三、執行結果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。