如何更新代码中的中点?
How can i update the midpoint in my code?
while(looper)
{
char higher = 'h';
char lower = 'l';
guess = getMidpoint(min,max);
char respons = getUserResponseToGuess(guess);
if(respons == 'c'){
looper = false;
}
else if(respons == higher)
{
min = min + 1;
getMidpoint(min,max);
}
else if(respons == lower)
{
max = min - 1;
getMidpoint(min,max);
}
}
public static int getMidpoint(int low, int high)
{
int midpoint;
midpoint = (high + low) / 2;
return midpoint;
}
所以基本上这是一个使用二分查找的猜谜游戏,getMidpoint方法得到两个数的中间值,min为1,max为100。h代表高,l代表低,c代表正确的。我一切都正确,但猜测总是很奇怪,就像它给我随机数一样。我如何更新最大值和最小值以使其正确?希望我的措辞是正确的。
else if(respons == higher)
{
min = min + 1;
getMidpoint(min,max);
}
else if(respons == lower)
{
max = min - 1;
getMidpoint(min,max);
}
这部分很奇怪。如果猜测应该更高,你应该做min = midpoint + 1
而不是只将min
增加1。当它应该更低,你应该做 max = midpoint - 1
.
你没有展示getMidpoint()
的实现,所以我不确定guess
是否可以用作新的min
/max
.
while(looper)
{
char higher = 'h';
char lower = 'l';
guess = getMidpoint(min,max);
char respons = getUserResponseToGuess(guess);
if(respons == 'c'){
looper = false;
}
else if(respons == higher)
{
min = min + 1;
getMidpoint(min,max);
}
else if(respons == lower)
{
max = min - 1;
getMidpoint(min,max);
}
}
public static int getMidpoint(int low, int high)
{
int midpoint;
midpoint = (high + low) / 2;
return midpoint;
}
所以基本上这是一个使用二分查找的猜谜游戏,getMidpoint方法得到两个数的中间值,min为1,max为100。h代表高,l代表低,c代表正确的。我一切都正确,但猜测总是很奇怪,就像它给我随机数一样。我如何更新最大值和最小值以使其正确?希望我的措辞是正确的。
else if(respons == higher)
{
min = min + 1;
getMidpoint(min,max);
}
else if(respons == lower)
{
max = min - 1;
getMidpoint(min,max);
}
这部分很奇怪。如果猜测应该更高,你应该做min = midpoint + 1
而不是只将min
增加1。当它应该更低,你应该做 max = midpoint - 1
.
你没有展示getMidpoint()
的实现,所以我不确定guess
是否可以用作新的min
/max
.