为什么代码不会显示数字?

时间:2016-03-29 09:37:27

标签: javascript

代码工作时代替document.write(total);我写前:

document.write((a*b)/(c*d)+"<br>");

这个问题在我最近的项目中发生了很多,同时试图学习这门语言

function calc(){ 
    for(x = 0; x < 5; x++){

    var a = Math.floor(Math.random() * 10 + 1) ;
    var b = Math.floor(Math.random() * 10 + 1) ;
    var c = Math.floor(Math.random() * 10 + 1) ;
    var d = Math.floor(Math.random() * 10 + 1) ; 
    var total += (a * b) / (c * d)  ;          

    document.write(total);
}

1 个答案:

答案 0 :(得分:3)

因为当您对增量分配total)进行了<{1>}时,+=未定义

应该是

var total = (a*b)/(c*d);   

或您的total变量应在for-loop

之外声明
function calc() {
  var total = 0;
  for (x = 0; x < 5; x++) {
    var a = Math.floor(Math.random() * 10 + 1);
    var b = Math.floor(Math.random() * 10 + 1);
    var c = Math.floor(Math.random() * 10 + 1);
    var d = Math.floor(Math.random() * 10 + 1);
    total += (a * b) / (c * d);
    document.write(total);
  }
}