我想創建一個程序,生成4個隨機數,將它們插入到數組中,然後將它們打印出來,但問題是它總是插入相同的數字,因爲我生成的數字與時鐘,它的速度太快,這是我的代碼:如何使裝配延遲
IDEAL
MODEL small
STACK 100h
DATASEG
Clock equ es:6Ch
EndMessage db 'Done',13,10,'$'
divisorTable db 10,1,0
randoms db 4 dup(11)
CODESEG
proc printNumber
push ax
push bx
push dx
mov bx,offset divisorTable
nextDigit:
xor ah,ah ; dx:ax = number
div [byte ptr bx] ; al = quotient, ah = remainder
add al,'0'
call printCharacter ; Display the quotient
mov al,ah ; ah = remainder
add bx,1 ; bx = address of next divisor
cmp [byte ptr bx],0 ; Have all divisors been done?
jne nextDigit
mov ah,2
mov dl,13
int 21h
mov dl,10
int 21h
pop dx
pop bx
pop ax
ret
endp printNumber
proc printCharacter
push ax
push dx
mov ah,2
mov dl, al
int 21h
pop dx
pop ax
ret
endp printCharacter
start:
mov ax, @data
mov ds, ax
; initialize
mov ax, 40h
mov es, ax
mov cx, 4
mov bx, offset randoms
RandLoop:
; generate random number, cx number of times
mov ax, [Clock] ; read timer counter
mov ah, [byte cs:bx] ; read one byte from memory
xor al, ah ; xor memory and counter
and al, 00001111b ; leave result between 0-15
mov [bx],al ;move the random number to the array
inc bx
loop RandLoop
; print exit message
mov cx, 4
mov bx, offset randoms
PrintOptions:
mov dl,[bx]
call printNumber
inc bx
loop PrintOptions
mov dx, offset EndMessage
mov ah, 9h
int 21h
exit:
mov ax, 4c00h
int 21h
END start
我覺得現在的問題是在這裏:
RandLoop:
; generate random number, cx number of times
mov ax, [Clock] ; read timer counter
mov ah, [byte cs:bx] ; read one byte from memory
xor al, ah ; xor memory and counter
and al, 00001111b ; leave result between 0-15
mov [bx],al ;move the random number to the array
inc bx
;call printNumber
loop RandLoop
這是一個X-Y問題。你的問題是你沒有得到好隨機生成的數字,所以你認爲解決方案是插入一個延遲。不是這樣。解決方案是使用更好的隨機數發生器。更重要的是,只用「一次*」的時間「種下」RNG,而不是每次循環。 –
@CodyGray你能給我一些代碼嗎? –
http://stackoverflow.com/questions/35583343/generating-random-numbers-in-assembly – vitsoft