我找到了this possible solution 但它给了我类似的东西:
598756802
373297426
-2011171535
它就像打印地址而不是数字值。怎么解决?
另外,我需要为发生器设置一个范围。就像生成0到99之间的随机数一样
我怎么能这样做?
Obs:已经尝试使用syscall 42
代码,但是我收到了错误
(OFF:至少告诉你downvote的原因,我没有水晶球)。
代码:
.text
li $v0, 41 # Service 41, random int
syscall # Generate random int (returns in $a0)
li $v0, 1 # Service 1, print int
syscall # Print previously generated random int
更新
这总是给我相同的数字,1000
。
.text
li $a1, 2501
li $v0, 42 #random
add $a0, $a0, 1000
li $v0, 1
syscall
答案 0 :(得分:2)
我可以使用以下代码:
.text
li $a1, 100 #Here you set $a1 to the max bound.
li $v0, 42 #generates the random number.
syscall
#add $a0, $a0, 100 #Here you add the lowest bound
li $v0, 1 #1 print integer
syscall
答案 1 :(得分:1)
你的最后一个代码块没有调用RNG系统调用,只调用了打印系统调用。
这很简单,您只需要执行以下操作
li $v0, 42 # 42 is system call code to generate random int
li $a1, 100 # $a1 is where you set the upper bound
syscall # your generated number will be at $a0
li $v0, 1 # 1 is the system call code to show an int number
syscall # as I said your generated number is at $a0, so it will be printed
如果要将生成的数字存储在数组中,这是一种方法:
move $s2, $s0 # copy the initial pointer to save array
li $v0, 42 # system call to generate random int
la $a1, 100 # where you set the upper bound
syscall # your generated number will be in $a0
sb $a0, 0($s2) # put the generated number at the position pointed by $s2
addi $s2, $s2, 1 # increment by one the array pointer
由于我们只需要0-100的范围,我们可以将每个数字存储在一个字节中,而不是使用sw
并将指针递增4。
答案 2 :(得分:0)
您需要生成随机数是改变上限,您将在寄存器$ s1中获得它。以下代码将生成范围为0..3
的随机数addi $v0, $zero, 30 # Syscall 30: System Time syscall
syscall # $a0 will contain the 32 LS bits of the system time
add $t0, $zero, $a0 # Save $a0 value in $t0
addi $v0, $zero, 40 # Syscall 40: Random seed
add $a0, $zero, $zero # Set RNG ID to 0
add $a1, $zero, $t0 # Set Random seed to
syscall
addi $v0, $zero, 42 # Syscall 42: Random int range
add $a0, $zero, $zero # Set RNG ID to 0
addi $a1, $zero, 4 # Set upper bound to 4 (exclusive)
syscall # Generate a random number and put it in $a0
add $s1, $zero, $a0 # Copy the random number to $s1