2013-04-10 62 views
1

我已經編寫了一半的程序。問題是我不知道如何編碼數學運算部分是提高m的功率爲n (m^n)。那麼,作爲初學者的任何建議?彙編程序(TASM)計算提升m到n的功率(m^n)

.MODEL SMALL 

.DATA 

greet db 13,10, "Welcome to Simple Calculator: Raise m to the power n. $" 
msg1 db 13,10, 0AH,0DH,"Please enter integer (m:-99 to 99): $" 
m  db 3,4 dup(?) 
msg2 db 10,13, 0AH,0DH,"Please enter power (n:1 to 9): $" 
n  db 3,4 dup(?) 
total db 10,13, "Answer: $" 


.CODE 

START: 

mov ax, seg greet 
mov ds, ax 
mov dx, offset greet 
mov ah, 09h  ;Display message 
int 21h 

mov ax, seg msg1 
mov ds, ax 
mov dx, offset msg1 
mov ah, 09h 
int 21h   ;Print a message 

mov ah, 0ah 
mov dx, offset m 
int 21h   ;Get 'm' value 


n_POWER: 

mov ax, seg msg2 
mov ds, ax 
mov dx, offset msg2 
mov ah, 09h 
int 21h   ;Print a message 

mov ah, 0ah 
mov dx, offset n ;Get 'n' value 
int 21h 

mov ax, m 
mov n, ax 
mul ax, n 
mov total, n 

finish: 
mov ah, 09h ;Display message 
int 21h 

mov ax,4c00h ;Return control to DOS 
int 21h   
end start 

另外,我如何從用戶(例如,-99)獲得的負輸入?

+0

我需要使用「JMP」命令嗎? – user2264387 2013-04-10 04:08:32

回答

1

您可以重複乘法,如:

int result = 1; while (exp-->0) { result *= base; } return result; 

或者,你可以/應該把指數在它的二進制表示:

5^13 = 5^(0b1101) = 1*(5^1)*(5^4)*(5^8) 

人們可以這樣反覆廣場副本的基數5:5→25→625→390625,然後乘以那些在指數的二進制表示中設置了相應位的術語。

這可能是矯枉過正的16位運算,但如果你的教授要求你進行模塊化求冪代替(如非對稱加密使用)這將是得心應手。

兩種方法都需要使用條件跳躍:

有條件地重複操作的一個簡單的做的cx數:

  mov cx, 13 
label: nop // put your block of code here 
     nop 
     loop label; // The instruction at label will be executed 13 times 
     // and cx will end up being zero 

要測試一個比特被設置,一個可以做

  mov dx, 13  ;; let's have the exponent here 
label: test dx, 1  ;; check if the first bit is zero 
         ;; test performs bitwise _and_ between the operand 
         ;; and sets ZERO flag (among other things) 
     jz notset  
     nop    ;; insert here the statements to be executed 
         ;; when the bit in the exponent is set 
notset: shr dx, 1  ;; shift out the least significant bit -- this also 
         ;; sets the ZERO_FLAG if dx goes to zero 
         ;; (and it eventually does) 
     jne label;  ;; 

btw。 JNE ==如果不等於則跳轉也測試零標誌。 如果不爲零則跳轉是同義詞。

+0

是的,謝謝你的幫助。但是,爲什麼我必須使用循環13次? '13'可以被'n'替代嗎? – user2264387 2013-04-10 08:42:32

+1

是的,你可以並應該用你的變量替換常量。你也應該填寫執行乘法和平方的指令。這絕不是一個完整的代碼塊被複制粘貼,因爲這會破壞學習的目的。 – 2013-04-10 09:07:59

+0

如果我想爲例如輸入。 '-99',我該怎麼辦?我必須轉換那些二進制文件?或者其他方式? – user2264387 2013-04-10 10:17:31

0

計算整數冪只是一系列乘法運算。例如,5^2 == 5 * 5,2^3 == 2 * 2 * 2等等。

因此,一個簡單的乘法循環就足夠了:

mov bx,5 ; m 
mov cx,3 ; n 
mov ax,1 ; Initial result, i.e. m^0 
power: 
    jcxz power_done 
    mul bx 
    loop power 
power_done: 
; ax now contains m^n 

注意,如果結果增長大於16位(除了隱含在最後一次迭代)我的示例代碼不處理的情況。它也不處理m的負值。如果您需要它們,我將把它作爲一個練習,讓您查找指令集參考,瞭解如何解決這些問題。

+0

爲什麼你需要jcxz(如果它是通用的情況下,爲什麼它的循環塊內?) – 2013-04-10 06:26:48

+0

爲了處理所有輸入一個自包含的循環塊> = 0的問題是不是最快的方法計算能力(在這種情況下,OP應該使用現代C/C++編譯器,並稱它爲一天)。 – Michael 2013-04-10 06:34:34

+0

的意思是,我可以用'm'替代常量'5'? – user2264387 2013-04-10 07:21:19