创建一个将温度从摄氏度转换为华氏度的 MASM 程序

问题描述 投票:0回答:1

我一直在

idiv dword ptr [NINE]
线上收到“整数溢出”。有没有另一种方法可以重写它以使我的 MASM 正常运行并在内存中给我答案 59°F?

.386
.model flat, stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD

.data
CelsiusTemperature DWORD 32

.code

; Function to convert Celsius to Fahrenheit
; Input: ecx - Celsius temperature
; Output: eax - Fahrenheit temperature
_convertC2F PROC
    push ebp                ; save the base pointer
    mov ebp, esp            ; set up the new base pointer
    sub esp, 4              ; reserve space for the return value
    mov eax, ecx            ; move the Celsius temperature to eax
    imul eax, 9             ; multiply by 9
    idiv dword ptr [NINE]   ; divide by 5
    add eax, 32             ; add 32 to get the Fahrenheit temperature
    mov dword ptr [ebp-4], eax ; store the Fahrenheit temperature on the stack
    mov eax, [ebp-4]        ; move the Fahrenheit temperature to eax
    mov esp, ebp            ; restore the stack pointer
    pop ebp                 ; restore the base pointer
    ret                     ; return from the function
_convertC2F ENDP

main PROC
    mov ecx, CelsiusTemperature ; set the Celsius temperature to the value in data
    call _convertC2F        ; call the function to convert to Fahrenheit
    ; eax now contains the Fahrenheit temperature
    ; do something with it here
    INVOKE ExitProcess, 0   ; exit the program
main ENDP

NINE DWORD 5

END main
assembly x86 masm masm32
1个回答
0
投票
NINE DWORD 5

把值5赋给一个名为NINE (9)的变量很奇怪
另外,你为什么不把这个变量放在你已经有一个

CelsiusTemperature
变量的 .data 部分?

mov eax, ecx            ; move the Celsius temperature to eax
imul eax, 9             ; multiply by 9
idiv dword ptr [NINE]   ; divide by 5
add eax, 32             ; add 32 to get the Fahrenheit temperature

你报告的错误存在是因为

idiv dword ptr [NINE]
指令划分寄存器组合EDX:EAX而你忘记事先初始化EDX。

; Function to convert Celsius to Fahrenheit
; Input: ECX - Celsius temperature
; Output: EAX - Fahrenheit temperature
; Clobbers: EDX
_convertC2F PROC
    imul eax, ecx, 9      ; multiply Celsius by 9, store to EAX
    cdq                   ; sign-extend EAX into EDX:EAX
    idiv dword ptr [FIVE] ; signed division of EDX:EAX by 5
    add  eax, 32          ; add 32 to get Fahrenheit
    ret                   ; return from the function
_convertC2F ENDP

因为您使用寄存器参数 (ECX) 调用 _convertC2F 函数并在 EAX 中返回结果,所以不需要在函数中包含那些序言/临时/结尾代码。

© www.soinside.com 2019 - 2024. All rights reserved.