简体   繁体   中英

Why won't the code display a number?

The code works when instead of document.write(total); I write ex:

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

this problem has occurred a lot in my recent projects while trying to learn this language

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);
}

Because your total was undefined at the time you did an increment-assignement ( += ) to it

it should be

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

or your total variable should be declared outside the 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM