猜数

猜数字小游戏

让程序自动生成一个数,让用户来猜,如果猜大了,就告诉用户猜大了,如果猜小了,就告诉用户猜小了,如果猜中了,就告诉用户猜中了并且停止程序

Scanner sc = new Scanner(System.in);
int num = (int) (Math.random() * 100 + 1);
int a = 0;
int count = 0;
do {
a = sc.nextInt();
count++;
if (a>num){
System.out.println("大了");
}else if (a<num){
System.out.println("小了");
}
}while (a!=num);
System.out.println("猜对了"+count+"次");

  使用Math.random()方法随机生成0-1之间的数让这个数*100+1,实现随机生成1-100之间的数,
  定义一个数用来计算猜数的次数,再循环进行判断,如果输入的数大于随机数,就输出猜大了,如果小于就输出猜小了,
运行结果:

 

 

 
posted @ 2022-06-08 17:08  xjw12345  阅读(137)  评论(0)    收藏  举报