1

私はすでにプログラムの半分をコーディングしました。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) ?

4

2 に答える 2

3

次のように乗算を繰り返すことができます。

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

または、バイナリ表現で指数を処理できる/処理する必要があります。

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

したがって、基数 5 のコピーを繰り返し2 乗することができます: 5 -> 25 -> 625 -> 390625 と、指数の 2 進数表現に対応するビットが設定されている項を乗算します。

これは 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;      ;;

ところで。JNE == 等しくない場合のジャンプでは、ゼロ フラグもテストされます。Jump if Not Zero と同義です。

于 2013-04-10T05:59:30.887 に答える
1

整数べき乗の計算は、単なる一連の乗算です。たとえば、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。必要に応じてこれらの問題を修正する方法については、命令セットのリファレンスを参照してください。

于 2013-04-10T05:34:52.190 に答える