Reputation: 11
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);
}
Upvotes: 0
Views: 32
Reputation: 68393
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);
}
}
Upvotes: 3