模块化程序设计(猜数字)(利用函数编程实现)

模块化程序设计(猜数字)

主函数=计算机随机数的生成+用户猜数字
细节:输入数据判断+数据范围控制+比较大小

函数片段:主要有四个部分:

数据读入+缓冲区非法数据清除+计数(随数据输入显示)

void GuessNumber(const int number)
{
	int guess,ret,count=0,right=0; 
	do
	{
		printf("try %d:",count+1);
		ret=scanf("%d",&guess);
		while(ret!=1||!IsvalidNum(number))//合法数据判断 
		{
			printf("error!\n");
			while(getchar()!='\n');          //缓冲区中非法字符清除 
		    printf("try %d:",count+1);
		    ret=scanf("%d",&guess);
		}
		count++;
		right=IsRight(number,guess);
	}while(!right&&count<=MAX_NUMBER);
	if(right)
	    printf("well!\n");
	else
	    printf("failed after %d attempts\n",MAX_TIMES);
}

越界数据的处理

int IsvalidNum(const int number)
{
	if(number>=MIN_NUMBER&&number<=MAX_NUMBER)
	    return 1;
    else
    	return 0;
 } 

猜数判断

int IsRight(const int number,const int guess)
 {
 	if(guessnumber)
	 {
	 	printf("too big!\n");
	    return 0; 
	  } 
	  else 
	  	return 1;
 }

int MakeNumber(void)
{
	int number;
	number=(rand()%(MAX_NUMBER-MIN_NUMBER+1))+MIN_NUMBER;
	assert(number>=MIN_NUMBER&&number<=MAX_NUMBER);
	return number;
}                           **//调用函数生成随机数,通过运算把数值控制在区间内** 

程序整体

#include
#include
#include
#include            //测试程序算法的正确性 
#define MAX_NUMBER 100
#define MIN_NUMBER 1
#define MAX_TIMES  10
int MakeNumber(void);//随机数生成 
void GuessNumber(const int number);//用户猜数实现 
int IsvalidNum(const int number);//输入数据的合法性检测 
int IsRight(const int number,const int guess);//判断两个数据的大小 
int main()
{
	int number;
	char reply;
	srand(time(NULL));
	do
	{
		number=MakeNumber();
		GuessNumber(number);
		printf("do you want to continue(Y/N or y/n)?");
		scanf("%c",&reply);
	}
	while(reply=='Y' or reply=='y');
	return 0;
}
int MakeNumber(void)
{
	int number;
	number=(rand()%(MAX_NUMBER-MIN_NUMBER+1))+MIN_NUMBER;
	assert(number>=MIN_NUMBER&&number<=MAX_NUMBER);
	return number;
}//调用函数生成随机数,通过运算把数值控制在区间内 

int IsRight(const int number,const int guess)
 {
 	if(guessnumber)
	 {
	 	printf("too big!\n");
	    return 0; 
	  } 
	  else 
	  	return 1;
 }

void GuessNumber(const int number)
{
	int guess,ret,count=0,right=0; 
	do
	{
		printf("try %d:",count+1);
		ret=scanf("%d",&guess);
		while(ret!=1||!IsvalidNum(number))//合法数据判断 
		{
			printf("error!\n");
			while(getchar()!='\n');//缓冲区中非法字符清除 
		    printf("try %d:",count+1);
		    ret=scanf("%d",&guess);
		}
		count++;
		right=IsRight(number,guess);
	}while(!right&&count<=MAX_NUMBER);
	if(right)
	    printf("well!\n");
	else
	    printf("failed after %d attempts\n",MAX_TIMES);
}
int IsvalidNum(const int number)
{
	if(number>=MIN_NUMBER&&number<=MAX_NUMBER)
	    return 1;
    else
    	return 0;
 } 

你可能感兴趣的:(模块化程序设计(猜数字)(利用函数编程实现))