明解C语言中级篇第一章练习

明解C语言中级篇第一章练习1-4

#include<stdio.h>
#include<time.h>
#include<stdlib.h>

int select_maxstage(int diff_num)
{
	int max_stage;
	if (diff_num >= 5000)
	{
		max_stage = 2;
	}
	else if (diff_num >= 2500)
	{
		max_stage = 3;
	}
	else if (diff_num >= 1000)
	{
		max_stage = 4;
	}
	else if (diff_num >= 250)
	{
		max_stage = 7;
	}
	else
	{
		max_stage = 9;
	}

	return max_stage;
}
int main()
{
	int record_num[9];
	int break_button = 0;//退出开关
	int remain=0;
	int max_stage;//最大次数
	int snum;//输入的猜测数字
	int rand_num1,rand_num2,diff_num;//随机数1,随机数2,两者之差
	int min_num, max_num;
	srand((int)time(NULL));
	rand_num1 = rand() % 10000;
	rand_num2 = rand() % 10000;
	diff_num = (rand_num1 > rand_num2) ? (rand_num1 - rand_num2) : (rand_num2 - rand_num1);
	max_num = rand_num1 > rand_num2 ? rand_num1 : rand_num2;//保存两个随机数中较大数值
	min_num = rand_num1 < rand_num2 ? rand_num1 : rand_num2;//保存两个随机数中较小数值
	//printf("%d,%d,%d", rand_num1, rand_num2, diff_num);   测试随机数差是否正确
	max_stage = select_maxstage(diff_num);
	printf("请猜测随机数的范围!只要选择在范围内即可通过!");
	do
	{
		printf("请输入你猜的数:");
		scanf_s("%d",&snum);
		record_num[remain++] = snum;//保存输入数据,并且实现remain自增
		printf("您还剩余%d次机会\n",max_stage-remain);
		if (snum<min_num)
		{
			printf("再大一点!\n");
		}
		else if(snum>max_num)
		{
			printf("再小一点!\n");
		}
		else
		{
			printf("恭喜你猜对了!\n");
			break_button = 1;
		}
	} while (break_button==0&&(max_stage-remain)>0);

	if (break_button==0)
	{
		printf("挑战失败!请继续努力!\n");
	}
	else
	{
		printf("挑战成功!\n");
	}

	for (int i = 0; i < remain; i++)
	{
		printf("第%d次:%d\n",i+1,record_num[i]);
	}

}
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页