C语言猜数字游戏
問題:
編寫一個猜數字的游程序,任意給一個1—100之間的整數,程序應能迅速的猜出此數是多少,每猜完一次數之后詢問是否繼續,若回答是則繼續做猜數游戲,若回答否,則結束程序運行。
分析:
rand()是“偽隨機數”產生函數,注意,是“偽隨機數”,而不是隨機數,如果每次srand()給的參數值都相同,那么rand()產生的序列就是相同的,time(NULL)返回的是從某年的1月1日0時0分0秒到系統當前時間所經過的秒數,所以如果不是同一秒鐘以內多次運行程序的話,time(NULL)的返回值一定是不同的,用這樣的方式來產生相對比較隨機的序列。在C語言頭文件<stdlib.h>中包含標準庫函數srand(),設置產生隨機數的種子。程序員可以在程序開始時自行設置種子的數值。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 main() 5 { 6 int a,b; 7 char c; 8 srand(time(NULL)); 9 a=1+(rand()%100); 10 printf("I have a number between 1 and 100.\nCan you guess my number?\nPlease type your first guess.\n"); 11 scanf("%d",&b); 12 while(b) 13 { 14 if(b==a) 15 { 16 printf("Excellent! You guessed the number!\nWould you like to play again(y or n)?"); 17 scanf(" %c",&c); //%c前面的空格不能少!用以隔離以前輸入的回車符 18 switch(c){ 19 case 'y': 20 printf("I have a number between 1 and 100.\nCan you guess my number?\nPlease type your first guess.\n"); 21 scanf("%d",&b); 22 break; 23 case 'n': 24 break; 25 } 26 } 27 28 while(b<a) 29 { 30 printf("Too low.Try again."); 31 scanf("%d",&b); 32 } 33 34 while(b>a) 35 { 36 printf("Too high.Try again."); 37 scanf("%d",&b); 38 } 39 } 40 }?
轉載于:https://www.cnblogs.com/geziyu/p/8734659.html
總結
- 上一篇: CTR预估中GBDT与LR融合方案
- 下一篇: Scala 隐式(implicit)详解