0

我正在使用 C++ 和汇编语言(8086)编写一个混合程序,以从数组中找到最小的数字。这是我的代码

#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
__int16 a[5],x,y,res;
int i,j;
y=999;

cout<<"\n Enter 5 Numbers:";
for(i=0;i<5;i++)
{
    cin>>a[i];
}

_asm{
    mov bx,y
}

//Finding smallest
for(i=0;i<5;i++)
{
    x=a[i];
    _asm{
        mov ax,x
        cmp ax,bx
        jge nxt
        mov bx,ax
        nxt:
    }
}

_asm{
    mov res,bx;
}

cout<<"\n Smallest Element:"<<res;
getch();
}

上面的代码是用 Visual Studio 2010 编写的,似乎运行良好。但是当我为 Turbo c++ 更新相同的代码时(即将“iostream”更改为“iostream.h”,删除“using namespace std;”,将“__int16”更改为“int”等),它不起作用。执行后产生的答案是错误的。

这是我的 TC++ 程序

#include<iostream.h>
#include<conio.h>
void main()
{
int a[5],x,y,res;
int i,j;
y=999;

cout<<"\n Enter 5 Numbers:";
for(i=0;i<5;i++)
{
    cin>>a[i];
}

_asm{
    mov bx,y
}

//Finding smallest
for(i=0;i<5;i++)
{
    x=a[i];
    _asm{
        mov ax,x
        cmp ax,bx
        jge nxt
        mov bx,ax
    }
    nxt:
}

_asm{
    mov res,bx;
}

cout<<"\n Smallest Element:"<<res;
getch();
}

为什么 TC++ 和 Visual Studio 10 没有给出相同的答案?

4

1 回答 1

0

您不能期望寄存器在程序集片段之间保留它们的值。你有三个汇编片段,它们之间有 C 块,它们依赖于bx保持不变。编译器没有做出这样的承诺。

要么使用内存来存储运行最小值,要么使用单个程序集片段重新制定。对于后一种方法,您必须在汇编中重写 for 循环和数组访问;这是非常可行的。像这样:

_asm{
mov dx, y ; we'll use dx instead of bx for the running minimum - long story
mov bx, a   ; that's the array pointer
mov si, 0 ; that's our i
loop:
    mov ax, [bx+si*2] ; read a[i] into ax; *2 because int is two bytes
    cmp ax,dx
    jge nxt
    mov dx, ax
    nxt:
    ;Now the for loop stuff
    inc si ; i++
    cmp si, 5 ; compare i to 5
    jl loop   ; if less, continue looping
; End of loop
mov res,dx;
}

我将 bx 和 si 用于基址+索引内存访问,因为在早期的 x86 CPU 上,您只能使用有限的寄存器子集(bx 或 bp 用于基址,si 或 di 用于索引)进行这种内存访问。如今,您可以使用任何寄存器组合;但我不确定古董 Turbo C 是否会接受。

于 2013-03-29T16:24:25.473 回答