随机数生成器用于if语句。 [英] Random Number Generator to be used in an if statement.

查看:149
本文介绍了随机数生成器用于if语句。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码,当通过下面的代码点击img时会发生这个功能。

 onclick =rollDice();





该函数调用ElementrollResult,然后成为...好......结果。



<前lang =HTML> < h2 id = rollResult > < / h2 >





这是我想成为好消息或坏消息的段落。



 <   p2     id   =  winOrLose >  <   / p2  >  





下面是单击img时执行的函数,它定义为rollResult元素时调用变量x然后我继续在'if'语句中与数字70进行比较。如果滚动的结果大于70,则你赢得任何低于70的其他滚动是一种损失。



  function  rollDice(){
var x = document .getElementById( rollResult);
x.innerHTML = 数学 .floor(( Math .random()* 100 )+ 1 );

如果(x> 70 ){
resultFinal = 你赢了。;
} else {
resultFinal = 你输了。;
}
document .getElementById( winOrLose)。innerHTML = resultFinal;

}





但是,经过测试,该按钮可以正常发出一个随机数生成一个然而,显示你赢了的消息。或者你输了。总是你失败了。无论我生成一个数字多少次,我认为我的'if'语句出了问题。



有人可以帮忙吗?

解决方案

您正在从RNG设置 x.innerHTML ,但随后在 x 中进行测试你的如果



干杯,

彼得


Here is the code, the function occurs when an img is clicked via the code below.

onclick="rollDice();"



The function calls upon the Element "rollResult" which then becomes the... well... result.

<h2 id="rollResult"></h2>



This is Paragraph that I would like to become the bearer of good or bad news.

<p2 id="winOrLose"></p2>



Below is the function executed upon clicking the img, it calls upon the rollResult element when defined as the variable "x" which I then go on to compare in an 'if' statement to the number 70. If result of the roll is greater than 70 you have won any other roll below 70 is a loss.

function rollDice() {
    var x = document.getElementById("rollResult");
    x.innerHTML = Math.floor((Math.random() * 100) + 1);
    
    if (x > 70) {
        resultFinal = "You've won.";
    } else {
        resultFinal = "You lose.";
    }
    document.getElementById("winOrLose").innerHTML = resultFinal;
    
}



However, when tested the button works fine issuing for a random number to be generated and one is displayed however the message of "You've won." or "You lose." is always "You lose." regardless of how many times I generate a number, something is wrong with my 'if' statement I think.

Can anyone help?

解决方案

You are setting x.innerHTML from the RNG, but then testing x in your if

Cheers,
Peter


这篇关于随机数生成器用于if语句。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆