我正在尝试用汇编语言创建一个程序,如果A> B,则双倍/平方B的值。
我能够输入单位数字,如5和3,答案应该是9,因为它表示当第一个数字大于第二个数字时,双倍/平方第二个数字。
不幸的是答案是错误的,它会产生“P2”作为答案。
pc macro x
mov ah, 02
mov dl, x
int 21h
endm
fl macro
int 20h
cseg ends
end start
endm
cls macro
mov ax, 0003h
int 10h
endm
cseg segment para 'code'
assume cs:cseg;ds:cseg;ss:cseg;es:cseg
org 100h
start:jmp begin
fn db ?
sn db ?
n db ?
m db ?
begin:
cls
mov ah,01
int 21h
sub al,30h
mov fn,al
mov ah,01
int 21h
sub al,30h
mov sn,al
cmp fn,al
ja x1
jmp exit
x1:
mul sn
cmp al,10
jae ilong
pc ' '
add al,30h
add ah,30h
mov n,al
mov m,ah
pc n
pc m
jmp exit
ilong:mov ah,0
mov al, n
mov bl,10
div bl
add al,30h ;div ah:al,bl
add ah,30h
mov n,al
mov m,ah
pc ' '
pc n
pc m
exit:fl
答案 0 :(得分:1)
对单个数字输入的数字进行操作,您的程序需要打印的最大结果是64(8 * 8)。当第一个数字是9而第二个数字是8时,你会得到这个。
您的计划有以下两个问题:
当结果确实小于10(0,1,4,9)时,你首先输出一个空格字符,但是你错误地尝试输出两位数需要显示一个数字!
cmp al, 10 ;AX is the product and AH is zero at this point!
jae ilong
add al, 30h ;Turn into text
mov n, al
pc ' '
pc n
jmp exit
当显示大于9(16,25,36,49,64)的结果时,你会立即开始销毁AX
寄存器中的计算平方(使用{{1 }} mov ah, 0
)。 此时请确认 n 变量没有定义值!
mov al, n
答案 1 :(得分:0)
如果a> b
/// ax = a
/// cx = b
/// return result in ax
cmp ax,cx ; a > b?
ja @SquareB ; yes, SquareB
ret ; no, done
,将b的值平方
@SquareB:
imul cx,cx ;b = b * b
mov ax,cx ;return b in ax (not sure if you need this step)
ret ;done
编写组合时,您需要为每一行代码编写注释 详细描述为什么您编码它以及您希望发生什么 如果你不这样做,那么第二天你就会努力去理解你自己的代码(别介意其他人试图理解你的推理)。
答案 2 :(得分:-1)
我纠正的解决方案:
; INPUT: AX= A
; CX= B
; OUTPUT: AX= (A>B) ? Sqr(B) : A
CMP AX,CX ; Compare input num. A with input num. B
JLE @Exit ; If A<=B, skip the multiplication and exit
MOV AX,CX ; Copy input num.B in accumulator AX
; Process ABS(B):
CMP AX,08000H ; 4 CPU-cycles, if num.B>=0 set carry flag
CMC ; 2 CPU-cycles, complements carry flag; if B<0 it is set
SBB CX,CX ; 3 CPU-cycles, if B<0, CX is set to -1 else is set to 0
XOR AX,CX ; 3 CPU-cycles, if B<0, do a 1-complement of num.B
SUB AX,CX ; 3 CPU-cycles, if B<0, do a 2-complement of num.B
; IMUL AX needs in the worst case up to 21 CPU-cycles more then MUL
MUL AX ; Multiply the absolute value of B for itself
@Exit:
RET ; Call's return
我的错误解决方案:
; INPUT: AX= A
; CX= B
; OUTPUT: AX= (A>B) ? Sqr(B) : A
CMP AX,CX ; Compare input num. A with input num. B
JLE @Exit ; If A<=B, skip the multiplication and exit
MOV AX,CX ; Copy input num.B in accumulator AX
NEG AX ; I MUSTN'T ALWAYS NEGATE AX, BUT ONLY IF AX<0!
MUL AX ; It multiply AX*AX and store the product in DX:AX
@Exit:
RET ; Call's return