我正在做一个年龄猜测项目,以测试我在Java,Python和JavaScript上的编程语言技能。Java和Python运行得相当稳定,没有太多的痛苦。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int age;
int power;
String response;
age = 64;
power = 5;
while (true) {
Scanner input = new Scanner(System.in);
System.out.print("Are you ");
System.out.print(age);
System.out.print(" years old? Answer with 'Yes', 'Older' or 'Younger'. Nothing else.");
response = input.next();
if (response.equals("Yes")){
System.out.print("Nice! You are ");
System.out.print(age);
break;
}
if (response.equals("Older")){
age = age + (int)(Math.pow(2, power));
power = power - 1;
}
if (response.equals("Younger")){
age = age - (int)(Math.pow(2, power));
power = power - 1;
}
if (power == -1){
System.out.print("Nice! You are ");
System.out.print(age);
break;
}
}
}
}
age = 64
power = 5
while True:
response = input("Are you {0} years old? Answer with 'Yes', 'Older' or 'Younger'. Nothing else.".format(age))
if response == "Yes":
print("Nice! You are {0} years old!".format(age))
break
if response == "Older":
age += (2**power)
power -= 1
if response == "Younger":
age -= (2**power)
power -= 1
if power == -1:
print("Nice! You are {0} years old!".format(age))
break
问题是JavaScript不工作。我先试了break,然后做了研究,发现break不起作用。在那之后,我尝试了一个终止符编号,其中循环在终止符编号为设置值时运行。有人能解释一下我的JS代码做错了什么,并给予这个bug的解决方案吗?
let age = 64;
let power = 5;
let terminatornum = 4
while (terminatornum == 4) {
let response = window.prompt("Are you " + age + " years old? Answer with 'Yes', 'Older' or 'Younger'. Nothing else.");
if (response == "Yes") {
console.log("Nice you are " + age + "years old!");
terminatornum -= 1;
}
if (response == "Older") {
age += (2**power);
power -= 1;
}
if (response == "Younger") {
age -= (2**power);
power -= 1;
}
if (power == -1) {
console.log("Nice you are " + age + "years old!");
terminatornum -= 1;
}
}
1条答案
按热度按时间edqdpe6u1#
Python代码的直接移植工作得很好: