【问题标题】:Struggling with the logic in if statement与 if 语句中的逻辑作斗争
【发布时间】:2015-10-18 01:30:29
【问题描述】:

所以我试图找到 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 中的。

【问题讨论】:

    标签: assembly mips


    【解决方案1】:

    您的逻辑是正确的,但您的 div 指令不正确。颠倒所有三个的论点。例如,你正在做s1 = s0 % t0,你想要s1 = t0 % s0

    警告:您不能在 mflo/mfhi 之后的两条指令内进行乘法/除法运算,因此您需要在这里和那里添加一个 nop。请参阅http://chortle.ccsu.edu/assemblytutorial/Chapter-14/ass14_5.html 特别是,您在 if2/if3 处的 div 在 fall through 案例中违反了这一点。

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

    变化:

        mfhi ...
        bne ...
    
    ifX:
        div ...
    

    进入:

        mfhi ...
        nop
        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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多