gpt4 book ai didi

javascript - 为什么变量总是输出 1,即使它在 Javascript 中递增

转载 作者:行者123 更新时间:2023-11-30 11:17:06 24 4
gpt4 key购买 nike

我尝试解决我在网上找到的一个问题。我成功地解决了这个问题,但是有一个小错误我无法解决。

问题

Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed.

这是我的代码:

// Generate a random number between 1 and 100
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;

while(running) {
var tries = 1;
var input = prompt("Take a guess");

if (input == num) {
console.log("Correct!");

console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}

Bug

Even if the user takes more than 1 try, the program still says,

Number of tries: 1

请解释我做错了什么。

谢谢。

最佳答案

您在 while 循环的每次迭代中重新初始化 tires:

while(running) {
var tries = 1;
...
}

尝试在循环外初始化。

var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
var tries = 1;

while(running) {
var input = prompt("Take a guess");

if (input == num) {
console.log("Correct!");

console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}

关于javascript - 为什么变量总是输出 1,即使它在 Javascript 中递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51123808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com