1. 題目:求X的階乘值
2. 要求:輸入一個整型數(不超過10),求出其階乘值后輸出,求階乘的算法用子程序來實現。
3. 提示:可以用遞歸來實現,也可以用簡單的循環來實現。
這里使用循環來實現:
對於匯編新手,最好通過高級語言的編程測試,然后再寫匯編代碼,這樣效果會好一些、
求階乘的C++代碼如下:
1 //The program is to find the factorial from 1 to 10 2 //author:Karllen 3 //Date: 05/21/2014 4 5 #include <iostream> 6 7 int factorial(int n); 8 9 int main() 10 { 11 int n; 12 std::cin>>n; 13 std::cout<<factorial(n)<<std::endl; 14 15 system("pause"); 16 return 0; 17 } 18 19 int factorial(int n) 20 { 21 int sum = 1; 22 while (n!=1) 23 { 24 sum*=n; 25 --n; 26 } 27 return sum; 28 }
匯編代碼如下:
1 ; Example assembly language program -- adds two numbers 2 ; Author: Karllen 3 ; Date: revised 05/2014 4 5 .386 6 .MODEL FLAT 7 8 ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD 9 10 INCLUDE io.h ; header file for input/output 11 12 cr EQU 0dh ; carriage return character 13 Lf EQU 0ah ; line feed 14 15 .STACK 4096 ; reserve 4096-byte stack 16 17 .DATA ; reserve storage for data 18 prompt BYTE "The program is to find the factorial from 1 to 10",cr,Lf,0 19 numInput BYTE "Please enter a number from 1 to 10",cr,Lf,0 20 answer BYTE "The number factorial is" 21 value BYTE 11 DUP(?) 22 BYTE cr,Lf,0 23 24 PUBLIC _start 25 .CODE 26 _start: 27 ; start of main program code 28 output prompt 29 30 doInput: 31 output numInput 32 input value,11 33 atod value 34 cmp eax,1 35 jl doInput 36 cmp eax,10 37 jg doInput 38 push eax 39 call findFactorial 40 add esp,4 41 42 dtoa value,eax 43 output answer 44 45 INVOKE ExitProcess, 0 ; exit with return code 0 46 ; make entry point public 47 48 findFactorial PROC NEAR32 49 push ebp 50 mov ebp,esp 51 52 mov eax,[ebp+8] 53 mov ebx,eax 54 cmp eax,1 55 je endFindWhile 56 doFindWhile: 57 dec ebx 58 cmp ebx,1 59 je endFindWhile 60 mul ebx 61 jmp doFindWhile 62 endFindWhile: 63 pop ebp 64 ret 65 findFactorial ENDP 66 END ; end of source code
測試結果:
