因此,对于我的java类,我们必须猜测用户在想什么号码,介于0和1024之间。我们必须猜测10个猜测中的数字。我不能在10个猜测中得到奇数,我只能在11中得到它们。这就是我到目前为止所做的:
import java.util.Scanner;
public class guessing_game {
public static void main(String[] args) {
int high, low, middle;
String input;
int totalGuesses;
high = 1024;
low = 0;
totalGuesses = 0;
String name;
System.out.println("What is your name?");
Scanner scan = new Scanner(System.in);
name = scan.nextLine();
middle = low + (high - low) / 2;
System.out.println("Is your number higher than " + middle + ", " + name + "? Please answer 'y' or 'n'. ");
System.out.println("If I guess the number, either answer 'that is my number' or answer 'n'.");
totalGuesses++;
Scanner sca = new Scanner(System.in);
input = sca.nextLine();
while (high - low != 1){
if (input.equals("y")){
low = middle;
middle = low + (high - low) / 2;
System.out.println("Okay, let's try again.");
System.out.println("Is your number higher than " + middle + ", " + name + "? ");
input = sca.nextLine();
totalGuesses++;}
if (input.equals("that is my number")){
System.out.println("Great! Your number is " + middle + ". ");
break;}
else if (input.equals("n")){
high = middle;
middle = low + (high - low) / 2;
System.out.println("Alright, I'll try again.");
System.out.println("Is your number higher than " + middle + ", " + name + "? ");
input = sca.nextLine();
totalGuesses++;}
if (high - low == 1){
System.out.println("Number is " + high);
break;}
if (high - low == 2){
System.out.println("Your number is " + high);
break;}}
System.out.println("This guessing game program used " + totalGuesses + " guesses.");
sca.close();
scan.close();
}
这是我的教授给我提供的p-code代码,文字帮助:
import java.util.Scanner;
Start of main method
integer high,low,middle;
String input;
integer totalGuesses;
high = 1024;
low = 0;
totalGuesses = 0;
start infinite loop
middle = low + (high - low)/2
print "Is your number higher than " + middle + " ? (y/n)"
increment totalGuesses by 1
read from keyboard into input
if input is “y”
low = middle
middle = low + (high - low)/2
if (high - low) == 1
print "Your number is " + high
exit the infinite loop
else
high = middle
middle = low + (high - low)/2
if (high - low) == 1
print "Your number is " + low
exit the infinite loop
print "The program used " + totalGuesses + " guesses"
end of method
课程结束
答案 0 :(得分:1)
middle = low + (high - low) / 2;
是奇数, high - low
将无法正确评估。由于除法发生在整数运算中,结果将是截断。