Using a random number generator in MIPS?

2019-09-06 12:06发布

So I was reading a few threads on this site and I found one on how to make one.. But I can't really find a link that explains more about how to code it.. My textbook for the course didn't provide any information about RNG at all so no help there.

The code was

li $a1, 4
li $v0, 42
add $a0, $a0, 1

is this correct for asking for a range between 1-3? I tried outputting what random number it was but it gave me the same number constantly.

#sw $a0, 0($s0)
li $a1, 4
li $v0, 42
add $a0, $a0, 1
#syscall

li $v0, 4
la $a0, Checking
syscall

li $v0, 1
move $t0, $a0
syscall

I saw the sw $a0, 0($s0) but I'm not sure what that does -- is it needed to output? (I took it out because after I pushed a key to go to the RNG, it said the program crashed) I keep getting the output of 268501267 which I'm not sure what that means edit: now it started giving me 268500992 all the time

Can anyone help explain this a little more in depth?

Logically speaking -- I understand the where the 42 comes from and why I need to add +1 (This is so I won't get the value of 0)

From there, I have no clue on why the code won't output a number in the range I gave.

1条回答
等我变得足够好
2楼-- · 2019-09-06 12:39

As stated by MARS documentation (Help > Syscalls):

random int 41 $a0 = i.d. of pseudorandom number generator (any int). $a0 contains the next pseudorandom, uniformly distributed int value from this random number generator's sequence

So

li $v0, 41         ; Service 41, random int
xor $a0, $a0, $a0  ; Select random generator 0
syscall            ; Generate random int (returns in $a0)

li $v0, 1  ; Service 1, print int
syscall    ; Print previously generated random int

Works fine for me, every time a different number is printed.

查看更多
登录 后发表回答