C语言动手训练营

C语言动手训练营

4 (19人评价)
  • 课时:(16)

  • 学员:(1027)

  • 浏览:(32477)

  • 加入课程

用C语言实现一个简单的猜数字游戏的笔记

相关课时: 笔记详情:

#include <stdio.h> //头文件输出

#include<time.h> //应该是时间

#include<stdlib.h> //里面定义的简单函数

#include<stdbool.h> //布尔类型头文件

#include<ctype.h> //返回非零值否则返回零

int main(){ //主函数

srand(time(NULL)) //每次运行随机数字

while(true) //循环

{

int min=1;

int max=100; //初始范围

int count=0; //猜测次数

const int target = rand ()%max + 1; //产生一个随机的目标数字

while (true) //猜测循环,内循环

{

 int guess = 0;

printf("please input a number between %d and %d\n",min,max); //输出这段话

fflush(stdin); //清空缓冲区

scanf("%d",&guess); //获取猜测的数字

++count; //猜测数字加一

if(guess<min || guess>max) //超出范围,判断

{

printf("the input is put of %d - %d\n",min ,max); //输出这段话

continue; //不执行循环剩下部分,直接进行下一次循环

}

else //否则

{

if (target == guess) //猜中

{

printf("YOU WIN! \nyou have guessed %d times in total.\n",count); //输出这段话

break; //跳出循环

}

else if (target > guess)  //目标比猜得数字大

{

min = guess;

printf("the target is larger than %d\n",guess); //输出这段话

}

else //目标比猜得数字小

{

max = guess;

printf("the target is less than %d\n",guess);

}

}

}

//本轮游戏结束

printf ("Do you want to play again?(Y - yes, N - no)\n"); //输出这段话

fflush (stdin); //请空缓冲区

char c = 'Y'; //定义一个字符

scanf ("%c",&c); //输入一个字符

if ( toupper (c) != 'Y') //判断是否不等于Y

break; //跳出循环

}

return 0; //返回值为零

}

0 0

你感兴趣的课程

5万+浏览/ 1756学员/ 3.8评分
免费
5万+浏览/ 926学员/ 4.5评分
免费