专注职业教育&教研设备+自媒体链接+智慧投资。
只要肯花时间,一定会有所成长。
学技术,重在日拱一卒、一点一滴的积累。
今天一起分析C语言的算法之10:猜字游戏。
算法题目:
猜1个一百以内的整数(该整数为系统随机产生的数),共5次机会。
编程思路分析
编程思路:
1、调用C语言库函数rand需要引用头文件stdlib.h,要让随机数限定在一个范围,可以采用模除加加法的方式。
2、要产生随机数r, 其范围为 m<=r<=n,可以使用如下公式:rand()%(n-m+1)+m,其原理为:对于任意数,0 <= rand()%(n-m+1) <= n-m;即rand()%(n-m+1)生成的随机数是在0到n-m之间的),于是0+m <= rand()%(n-m+1)+m <= n-m+m(于是给这个随机数加上m就可以得到m到n-m之间的随机数)即m<=rand()%(n-m+1)+m<=n。
3、所以循环13次即可。
程序范例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num;
int guess;//用户猜数
int right;//正确答案
int count;//已猜次数
int c;
srand((unsigned)time(0));
while(1)
{
count = 0;
right = 0;
num = rand()%100;
printf("请猜一个数:");
while(count++ < 5)
{
/*小于5次,不断猜数*/
scanf("%d",&guess);
if(guess == num)
{
right = 1;
printf("恭喜猜对!\n");break;
}
else if(guess>num)
rintf("大.\n");
else
printf("小.\n");
}
if(right == 0)
printf("尝试5次,失败\n");
printf("是否继续?y/n:");
fflush(stdin);
c = getchar();
if(c == 'n' || c == 'N')
break;
}
return 0;
}
程序运行结果案例:
祝各位朋友:
春节快乐;
阖家团圆;
幸福美满。