Assembly 与if语句中的逻辑抗争

Assembly 与if语句中的逻辑抗争,assembly,mips,Assembly,Mips,所以我试图找出3个数字之间的最大公分母。我认为我的逻辑是相当健全的,如何做到这一点,我目前没有得到正确的输出 li $s0, 1 whileloop: bgt $s0, $t0, exit bgt $s0, $t1, exit bgt $s0, $t2, exit IF1: div $s0, $t0 mfhi $s1 bne $s1, $zero, else IF2: div $s0, $t1 mfhi $s2

所以我试图找出3个数字之间的最大公分母。我认为我的逻辑是相当健全的,如何做到这一点,我目前没有得到正确的输出

li $s0, 1 

whileloop:
bgt $s0, $t0, exit 
bgt $s0, $t1, exit 
bgt $s0, $t2, exit 
    IF1:
    div $s0, $t0 
    mfhi $s1 
    bne $s1, $zero, else  


  IF2: 
    div $s0, $t1
    mfhi $s2 
    bne $s2, $zero, else  

   IF3:
   div $s0, $t2 
   mfhi $s3 
   bne $s3, $zero, else 
   sw $s0, 4($s4)
   j else 

    else: 
    addi $s0, $s0, 1 
    j whileloop 


exit: 

    la $a0, answer 
    syscall 

    move $a0, $s4 
    li $v0, 1 
    syscall 

    li $v0, 10 
    syscall 

这三个数字由用户输入到$t0、t1和$t2中

您的逻辑正确,但div指令不正确。把这三个问题的论点都颠倒过来。例如,您正在执行
s1=s0%t0
并且希望
s1=t0%s0

警告:在mflo/mfhi之后,不能在两条指令内进行乘法/除法运算,因此需要在此处和此处添加nop。请特别注意,您在if2/if3的部门在fall-through案例中违反了这一点

就我个人而言,我会在mfhi之后而不是在div之前更改它来解决这个问题。IMO,这更干净,因为限制来自mfhi[而不是div],所以将补偿与之关联。而且,为了规范起见,我会把它放在所有三个mfhi上,即使其中一个实际上并不需要它

更改:

    mfhi ...
    bne ...

ifX:
    div ...
进入:

为了好玩,以下是您的程序翻译回C:

int
gcd(int t0,int t1,int t2)
{
    int s0;
    int s1;
    int s2;
    int s3;
    int rtn;

    rtn = -1;

    s0 = 1;

Lloop:
    if (s0 > t0) goto Lexit;
    if (s0 > t1) goto Lexit;
    if (s0 > t2) goto Lexit;

Lif1:
#if 0
    s1 = s0 % t0;
#else
    s1 = t0 % s0;
#endif
    if (s1 != 0) goto Lelse;

Lif2:
#if 0
    s2 = s0 % t1;
#else
    s2 = t1 % s0;
#endif
    if (s2 != 0) goto Lelse;

Lif3:
#if 0
    s3 = s0 % t2;
#else
    s3 = t2 % s0;
#endif
    rtn = s0;
    if (s3 != 0) goto Lelse;

Lelse:
    s0 += 1;
    goto Lloop;

Lexit:
    return rtn;
}
int
gcd(int t0,int t1,int t2)
{
    int s0;
    int s1;
    int s2;
    int s3;
    int rtn;

    rtn = -1;

    s0 = 1;

Lloop:
    if (s0 > t0) goto Lexit;
    if (s0 > t1) goto Lexit;
    if (s0 > t2) goto Lexit;

Lif1:
#if 0
    s1 = s0 % t0;
#else
    s1 = t0 % s0;
#endif
    if (s1 != 0) goto Lelse;

Lif2:
#if 0
    s2 = s0 % t1;
#else
    s2 = t1 % s0;
#endif
    if (s2 != 0) goto Lelse;

Lif3:
#if 0
    s3 = s0 % t2;
#else
    s3 = t2 % s0;
#endif
    rtn = s0;
    if (s3 != 0) goto Lelse;

Lelse:
    s0 += 1;
    goto Lloop;

Lexit:
    return rtn;
}