//bullcow3.c /* 這也是可以RUN 的程式 (想出四位不同數字 --- 給 Bull&Cow GAME 用的) 這程式在這: ftp.csie.nctu.edu.tw /pub/CSIE/course/cs2/bullcow3.c * * *Again, 再給那個 公牛母牛遊戲 (又叫 幾 A 幾 B 遊戲) 更多提示 * * * How to generate four different digits? *** Try the following program: ( get the program bullcow3.c from our ftp site) 或是由 ccsun?? 直接 cp /net/ftp/pub/CSIE/course/cs2/bullcow3.c . *************************************************/ #include #include #include #define repeat do{ #define until(x) }while(!(x)) char mynum[5], yourguess[5]; char x; int myrandom(); /* I will write it later on */ int main() { int k, seed; mynum[4] = 0; /* same as '\0' */ printf("讓我想好四位數字...\n"); /****** 去掉這列再 run 看看 ****** seed = (int) time(0) & 0xffff; srand( seed ); /*** set seed ***/ #ifdef DEBUG printf("seed=%d===\n", seed); /***/ #endif mynum[0] = myrandom(); repeat x= myrandom(); until (x != mynum[0]); mynum[1] = x; x= myrandom(); while( x== mynum[0] || x == mynum[1]) /* 注意條件 */ x= myrandom(); mynum[2] = x; repeat x= myrandom(); until ( (x != mynum[0]) && x!= mynum[1] && x!= mynum[2]); mynum[3] = x; for(k=0; k<=3; k++) mynum[k] += '0'; /* convert to ASCII */ printf("我想好的是: %s\n", mynum); } int myrandom() { int ans= rand(); return ans % 10; /* 0..9 */ } /*********** Q: 為何此例生出的數字總是 0541 ? A: 因為 pseudo random 啊 注意看程式中那列 " /****** 去掉這列再 run 看看 ****** " 若要真 random, 可利用 time() 取一值做 rand() 的 seed (種子) 在主程式一開始先 叫用 srand( time(0) ); 就會變啦 see "man 3 rand" 和 "man 3 srand" 以及 "man 3 time" ***********************************************************/