计算机假定一个数,用户猜
因为要用户不断猜,需要用循环
写程序之前,用文字描述思路
循环条件和终止是重点
步骤
1.计算机随机想,记在number里
2.算次数count初始化0
3.让用户输入数字a
4.count递增
5.判断a与number大小关系,输出“大”“小”
6.如果a与number是不相等,程序跳回步骤3
7.否则,输出“猜中”和次数,结束
循环的条件是a和number不等(与自己想的要相反)
public class Hello {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = (int)Math.random()*100+1; // [0,1) -->[1,100]-->[1,100]
int a;
int count = 0;
do{
a = in.nextInt();
count = count + 1;
if( a > number)
{
System.out.println("偏大");
}
else if (a < number)
{
System.out.println("偏小");
}
}while (a !=number );
System.out.println("恭喜猜对了,你猜了"+count+"次");
}
}
100只要7次就可以找到