Alex Ventisei
Alex Ventisei

Reputation: 1

Why does this canvas code not work?

I have been playing about with the random number generator on the Khan academy website. This is the code that I have entered into the console. I know that there is no ctx stuff there but the code is very similar to working with a normal HTML canvas. I am trying to get the canvas to show a bar chart of cumulative frequency, showing how many times the random number generator has picked each number. To do this I am trying to take the total amount of times that each number has come up, and then use that as the variable for the height of each bar in the chart.

    var num_1 = 0;
    var num_2 = 0;
    var num_3 = 0;
    var num_4 = 0;
    var num_5 = 0;
    var num_6 = 0;
    var num_7 = 0;
    var num_8 = 0;
    var num_9 = 0;
    var num_10 = 0;

    var draw = function() {      //the draw function just repeats the stuff inside it every second
    var random_num = random(0,10);

    if(random_num === 1){
        num_1 = num_1 + 1;
    }else if(random_num === 2){
        num_2 = num_2 + 1;
    }else if(random_num === 3){
        num_3 = num_3 + 1;
    }else if(random_num === 4){
        num_4 = num_4 + 1;
    }else if(random_num === 5){
        num_5 = num_5 + 1;
    }else if(random_num === 6){
        num_6 = num_6 + 1;
    }else if(random_num === 7){
        num_7 = num_7 + 1;
    }else if(random_num === 8){
        num_8 = num_8 + 1;
    }else if(random_num === 9){
        num_9 = num_9 + 1;
    }else if(random_num === 10){
        num_10 = num_10 + 1;
    }
    fill(122, 116, 116);
    rect(height, width/10, 20, num_1);
    rect(height, width/9, 20, num_2);
    rect(height, width/8, 20, num_3);
    rect(height, width/7, 20, num_4);
    rect(height, width/6, 20, num_5);
    rect(height, width/5, 20, num_6);
    rect(height, width/4, 20, num_7);
    rect(height, width/3, 20, num_8);
    rect(height, width/2, 20, num_9);
    rect(height, width/1, 20, num_10);
 };

Upvotes: 0

Views: 116

Answers (1)

KRLW890
KRLW890

Reputation: 63

Your problem is quite simple. You have your if statements react if the random number exactly equals a whole number. The random function chooses a random number with a decimal. There are two very easy ways to solve this.

1) Have

random_num = round(random(0,10));

or

2) Use > and < signs in your if statements. ex:
make sure you start with "> 2", if you don't already know.

var random_num = random(1, 11)

-skipping some code here-

if (random_num < 2) {(too lazy to copy code in here)}  
else if (random_num < 3) {(again)}  
*ect.*

I personally find the first o be the easiest.

Upvotes: 0

Related Questions