数値の階乗
数値の階乗を求めるプログラムです。数値 n の階乗 (n! と表記) は、1 から n までのすべての自然数の積です。
プログラムのソースコード
title .model small .stack 100h data segment public askUser db "Enter a number to find its factorial: \0" fmtoutput db "\nThe factorial of this number is: %d\0" fmtinput db "%d" number dw ? factorial dw 1 data ends code segment public ; コードセグメントの開始 assume ds:data, cs:code include Handyfar.inc ; 関数を含むファイルをインクルードする main proc ; プロシージャ main の開始 call SetDataSegment ; プロシージャ SetDataSegment を呼び出す lea ax, ds:[askUser] ; 変数 askUser のアドレスをレジスタ ax にロードする call WriteString ; プロシージャ WriteString を呼び出す lea ax, ds:[number] ; 変数 number のアドレスをレジスタ ax にロードする push ax ; 2 番目: レジスタ ax の値をスタックに保存する lea ax, ds:[fmtinput] ; 1 番目: 書式文字列 fmtinput のアドレスをレジスタ ax にロードする call ScanFormatString ; プロシージャ ScanFormatString を呼び出す add sp, 2 ; スタックを調整する mov cx, 1 ; カウンタを 1 に設定する MainLoop: mov ax, factorial ; 変数 factorial の値をレジスタ ax にコピーする mul cx ; レジスタ ax の値と cx の値を乗算する mov factorial, ax ; 結果を変数 factorial に保存する inc cx ; カウンタレジスタの値を 1 増やす cmp cx, number ; cx の値と変数 number の値を比較する jbe MainLoop ; 値が userInput 以下なら、MainLoop にジャンプする push factorial ; 2 番目: 変数 factorial の値をスタックに保存する lea ax, ds:[fmtoutput] ; 1 番目: 書式文字列 fmtoutput のアドレスをレジスタ ax にロードする call PrintFormatString ; プロシージャ PrintFormatString を呼び出す add sp, 2 ; スタックを調整する xor al, al ; レジスタ al をゼロにする call ExitProcess ; プロシージャ ExitProcess を呼び出す main endp ; プロシージャ main の終了 code ends ; コードセグメントの終了 end main ; ファイルの終わり。エントリポイントとしてプロシージャ main を指定する
Enter a number to find its factorial: 5
The factorial of this number is: 120
例は教科書 "HANDYFAR - MASM (Evgeny Dovgopolov)".