输入一个数N,对1到N的所有自然数求和
程序运行:
代码:
datas segmentN_string_max_length db 0ffhN_string db 0, 100h dup(?)N dw 0 sum dd 0 input db 'input N=$'output db 0dh,0ah,'output sum=$'datas endsstacks segment stackdb 100h dup(?)stacks endscodes segmentassume cs:codes,ds:datas,ss:stacks
main proc far
start:push dsmov ax,0hpush axmov ax,datas ;初始化dsmov ds,ax;输入提示lea dx,inputmov ah,9int 21h;输入Nlea dx,N_string_max_lengthmov ah,10 int 21h;转换成为数字lea si,N_stringcall todigitmov N,axmov ax,0 mov dx,0mov cx,N ;循环的次数mov bx,1 ;求和从一开始s:add ax,bx ;求和adc dx,0 inc bx loop smov word ptr sum,ax ;保存求和的结果mov word ptr sum+2,dxlea dx,output ;输出提示mov ah,9int 21h mov ax,word ptr sum ;输出求和mov dx,word ptr sum+2call print_decimalretmain endptodigit proc near uses bx cx dx si di ;si ,axmov cl,[si] ;设置循环次数xor ch,ch inc si ;si指向第一个元素mov ax,0 ;初始化ax,dxmov dx,0 mov di,10 ;除数dig:mov bl,[si] cmp bl,'0' ;判断是否小于'0'jb err ;若低于'0',则错误字符cmp bl,'9' ;判断是否大于'9'ja err ;若高于'9',则错误字符sub bl,30h ;否则,将数字字符转成数字xor bh,bh mul di ;乘十add ax,bx ;加上个位adc dx,0 inc siloop digcmp dx,0 ;判断高位是否为0jnz err ;若不为0,错误jmp exit err: ;输出错误push ds push cs pop ds lea dx,error_tip mov ah,9int 21hpop dsmov ah,4ch int 21hexit:ret error_tip db 0dh,0ah,'input error$'
todigit endpprint_decimal proc near uses ax bx cx dx mov bx,10 mov cx,0 dea: div bx push dx inc cx xor dx,dx cmp ax,0 jnz deadea1:pop dxadd dl,30hmov ah,2int 21hloop dea1 ret
print_decimal endp
codes endsend main