无法弄清楚公式有什么问题

时间:2017-05-19 16:19:17

标签: javascript html css

var johnHeight = prompt('Enter the height');

var johnAge =prompt('Enter the age');

var ranaHeight = prompt('Enter the height');

var ranaAge =prompt('Enter the age');   

var johnScore = johnHeight + 5 * johnAge;

var win = document.getElementById('winner');

if (johnScore > ranaScore) {

        win.innerHTML = 'John is the winner with ' + johnScore + ' points';

}

else if (johnScore < ranaScore) {

    win.innerHTML = 'Rana is the winner with ' + ranaScore + ' points';
}

else if (johnScore == ranaScore) {

    win.innerHTML = 'It\'s a draw';
}

当我尝试运行代码时,一切正常,但公式即JohnScore或ranaScore无法计算正确的值。 当我删除提示并给这些变量一个预定义的值,它工作正常.. 请有人解决。

4 个答案:

答案 0 :(得分:0)

你没有为ranaScore设置变量,如果你的意思是在他的身高上加5,然后乘以年龄,这意味着它必须是:

var johnScore = (johnHeight + 5) * johnAge;

如果那不是您所需要的,您可以尝试:

var johnScore = johnHeight + (5 * johnAge);

答案 1 :(得分:0)

来自提示的值以字符串形式出现。因此,要获得正确的计算,您需要将其转换为数字。提示前请注意+。 您还需要定义ranaScore

因此,如果johnHeight为“10”且johnAge为“5”,那么让我们看看这是如何通过javascript进行评估的:

var johnScore = johnHeight + 5 * johnAge;

johnScore = "10" + 5* "5" which is "10" + "25" which is "1025".

var johnHeight = +prompt('Enter the height');

var johnAge = +prompt('Enter the age');

var ranaHeight = +prompt('Enter the height');

var ranaAge = +prompt('Enter the age');

var johnScore = johnHeight + 5 * johnAge;
var ranaScore = ranaHeight + 5 * ranaAge;
var win = document.getElementById('winner');

if (johnScore > ranaScore) {

  win.innerHTML = 'John is the winner with ' + johnScore + ' points';

} else if (johnScore < ranaScore) {

  win.innerHTML = 'Rana is the winner with ' + ranaScore + ' points';
} else if (johnScore == ranaScore) {

  win.innerHTML = 'It\'s a draw';
}
<div id="winner"></div>

答案 2 :(得分:0)

看起来您的变量ranaScore尚未定义,因此您需要此行。

            var ranaScore = rannaHeight + 5 * rannaAge;

虽然在现实生活中你需要构建你的JS函数来接收参数而不是使用静态变量,例如,参见下面的基本示例。

            function comparevalues(arg1,arg2){
                if (arg1 > arg2) {
                    win.innerHTML = arg1 + 'is greater than ' + arg2; //arg 1 wins
                }
                else if (arg1 < arg2) {
                    win.innerHTML = arg2 + 'is greater '  + arg1; //arg 2 wins
                }
                else {
                    win.innerHTML = arg2 + 'is equal to '  + arg1; //draw
                }
            }
            comparevalues(4,5)

答案 3 :(得分:0)

始终提示返回字符串类型,使用ParseInt方法将其转换为数字。 var johnHeight = parseInt(提示(&#39;输入高度&#39;));