幂运算

计算任意数字的幂的程序。

程序源代码

title Author: Dovgopolov Evgeny Sergeevich

.model small
.stack 100h

data segment public
    askUserBase db "Enter the base: \0"
    askUserExp  db "\nEnter the exponent: \0"
    msgres      db "\nResult: %d\0"
    fmtBase     db "%d"
    fmtExponent db "%d"
    base        dw ?
    exponent    dw ?
    number      dw 1
data ends

code segment public                   ; 代码段的开始
    assume  ds:data, cs:code
    include Handyfar.inc              ; 引入包含函数的文件

    main proc                         ; 过程 main 的开始
        call    SetDataSegment        ; 调用过程 SetDataSegment

        lea     ax, ds:[askUserBase]  ; 把变量 askUserBase 的地址装入寄存器 ax
        call    PrintFormatString     ; 调用过程 PrintFormatString

        lea     ax, ds:[base]         ; 把变量 base 的地址装入寄存器 ax
        push    ax                    ; 第 2 个:把寄存器 ax 的值保存在堆栈中
        lea     ax, ds:[fmtBase]      ; 第 1 个:把格式字符串 fmtBase 的地址装入寄存器 ax
        call    ScanFormatString      ; 调用过程 ScanFormatString
        add     sp, 2                 ; 对齐栈

        lea     ax, ds:[askUserExp]   ; 把变量 askUserExp 的地址装入寄存器 ax
        call    PrintFormatString     ; 调用过程 PrintFormatString

        lea     ax, ds:[exponent]     ; 把变量 exponent 的地址装入寄存器 ax
        push    ax                    ; 第 2 个:把寄存器 ax 的值保存在堆栈中
        lea     ax, ds:[fmtExponent]  ; 第 1 个:把格式字符串 fmtExponent 的地址装入寄存器 ax
        call    ScanFormatString      ; 调用过程 ScanFormatString
        add     sp, 2                 ; 对齐栈

        mov     ax, number            ; 把变量 number 的值复制到寄存器 ax
        mov     bx, base              ; 把变量 base 的值复制到寄存器 bx
        mov     cx, 1                 ; 把计数器设为 1

    MainLoop:
        mul     bx                    ; 把寄存器 ax 中的值乘以 bx 中的值

        mov     number, ax            ; 把结果保存到变量 number

        inc     cx                    ; 把计数寄存器的值增加 1
        cmp     cx, exponent          ; 把 cx 的值与 exponent 中的值进行比较
        jbe     MainLoop              ; 如果该值小于或等于 exponent,则跳转到 MainLoop

        push    number                ; 第 2 个:把变量 number 的值保存在堆栈中
        lea     ax, ds:[msgres]       ; 第 1 个:把变量 msgres 的地址装入寄存器 ax
        call    PrintFormatString     ; 调用过程 PrintFormatString
        add     sp, 2                 ; 对齐栈

        xor     al, al                ; 把寄存器 al 清零
        call    ExitProcess           ; 调用过程 ExitProcess
    main endp                         ; 过程 main 的结束

code ends                             ; 代码段的结束
end main                              ; 文件结束。入口点指定为过程 main

Enter the base: 2
Enter the exponent: 5
Result: 32

示例取自教材 "HANDYFAR - MASM(多夫戈波洛夫·叶夫根尼·谢尔盖耶维奇)".