Object
我想到了一个数字22,当它问我数字是否为50时输入2.然后它立即转到1.无论我输入什么,它显示1作为输出而不是像50,25, 12等我在Python和C中做了同样的事情,它们运行得很好。
答案 0 :(得分:4)
将high = ans
和low = ans
替换为high = guess
,low = guess
- 将相应的“猜测范围”边界移动到输入值(1或2),但是至于先前猜测的值,如二元搜索。
答案 1 :(得分:4)
好的,第一个问题是您将ans
分配给high
和low
而不是guess
。
然后,如果我能给你一些建议:
x
扫描仪if/else
块中放置常见操作。相反,将常见操作放在外面。这是一个改进版本,但我相信你可以做得更好:
public static void main( String[] args ){
System.out.println( "Welcome to Siddharth's number guessing game. \nThink of a number between 1 and 100 and "
+ "press 1 to continue" );
Scanner x = new Scanner( System.in );
if( x.nextInt() == 1 ){
int high = 100;
int low = 0;
int guess = ( high + low ) / 2;
System.out.println( "Is your number " + guess + "? Press 0 if yes, press 1 if your number is higher than " +
"this number or press 2 if your number is lower than this number!" );
while( true ){
int ans = x.nextInt();
if( ans == 0 ){
break;
}else if( ans == 1 ){
low = guess;
}else if( ans == 2 ){
high = guess;
}
guess = ( high + low ) / 2;
System.out.printf( "Is your number %d ? (0: yes, 1: higher, 2:lower) ", guess );
}
System.out.println( "The number you thought of is " + guess + "! Thanks for playing!" );
}else{
System.out.println( "No problem. Restart the program and press 1 when ready!" );
}
}