我编写了以下程序来获取数字的阶乘:
section .data
result_msg db 'Factorial: ', 0
newline db 10
section .text
global _start
_start:
; Constants
mov eax, 5 ; Number for which factorial is to be calculated
; Initialize result to 1
mov ebx, 1 ; Result
; Loop to calculate factorial
fact_loop:
cmp eax, 1
jle print_result
; Multiply current result by the current number
imul ebx, eax
; Decrement the number
dec eax
jmp fact_loop
print_result:
; Print "Factorial: "
mov eax, 4
mov ebx, 1
mov ecx, result_msg
mov edx, 10 ; Updated to the correct length of the message
int 0x80
; Convert the result to ASCII and display it
add ebx, '0' ; Convert the result to ASCII
mov eax, 4
mov ecx, ebx ; Use ebx directly as the result
mov edx, 1
int 0x80
; Print newline
mov eax, 4
mov ebx, 1
lea ecx, [newline]
mov edx, 1
int 0x80
; Exit program
mov eax, 1
xor ebx, ebx
int 0x80
我遇到的问题是它只打印字符串“Factorial”而不是 120。我正在使用以下在线编译器:
https://rextester.com/l/nasm_online_compiler
我的解决方案中缺少什么?
谢谢
ebx 包含一个整数,而不是指向字符串的指针,因此它无法正确打印。您需要将 ebx 中的值转换为字符串才能打印它,类似于 https://stackoverflow.com/a/13523734/5938339.