游戏规则:输入整数范围,根据系统给出提示进行猜数,每猜一次减少一次机会,猜中或者机会耗尽则一轮游戏结束。
游戏示例:输入范围0-4,你可以猜数1,2,3,系统提示有一次猜数机会
如果你猜1,如果猜中,系统显示“恭喜你,猜对了”,否则将显示“猜错了,正确结果为XXX”。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> int main(void){ int guess_cishu=0; int guess_cishu1=0; int guess_cishu2=0; int up_limit=0; int down_limit=100; int caishu=1; int result; char cmd[10]; double random_number; while(1){ srand((unsigned)time(NULL)*100); printf("输入start开始游戏,输入end结束游戏 "); scanf("%s", cmd); //用fgets会出问题,why if(memcmp(cmd, "end", 3)==0) break; else if(memcmp(cmd, "start", 5)==0){ memset(cmd, 0, 10); random_number = (double)rand()/RAND_MAX; printf("请输入猜数范围 "); printf("范围上限:"); scanf("%d", &up_limit); printf("范围下限:"); scanf("%d", &down_limit); if(up_limit>=down_limit-2){ printf("范围不合理,请重新输入 "); continue; } guess_cishu = (int)(log10((double)down_limit-up_limit-1)/log10((double)2)); printf("你有%d次猜的机会 ", guess_cishu); while(1){ printf("输入要猜的数字:"); scanf("%d", &caishu); if(caishu>=down_limit||caishu<=up_limit){ printf("输入的数字非范围内 "); continue; } else{ random_number = (double)rand()/RAND_MAX; guess_cishu --; guess_cishu1 = (int)(log10((double)caishu-up_limit-1)/log10((double)2)); guess_cishu2 = (int)(log10((double)down_limit-caishu-1)/log10((double)2)); if(guess_cishu==guess_cishu1&&guess_cishu==guess_cishu2){ if(random_number<0.5) up_limit=caishu; else down_limit=caishu; } else if(guess_cishu==guess_cishu1){ down_limit = caishu; } else{ up_limit = caishu; } /* if(caishu>(up_limit+down_limit)/2){ down_limit = caishu; } else if(caishu<(up_limit+down_limit)/2){ up_limit = caishu; } else{ if(random_number<0.5) up_limit = caishu; else down_limit = caishu; }*/ if(guess_cishu>0){ printf("你猜错了,你还可以再猜%d次,范围是%d-%d ", guess_cishu, up_limit, down_limit); } else break; } } random_number = (double)rand()/RAND_MAX; result = floor(random_number*(down_limit-up_limit-1))+up_limit+1; printf("哈哈,猜错了,正确答案是%d ", result); //用随机数输出结果 } else{ printf("未知指令 "); memset(cmd, 0, 10); } } printf("用户结束游戏 "); system("pause"); return 0; }
我们来看结果: