在if语句逻辑挣扎 [英] Struggling with the logic in if statement

查看:250
本文介绍了在if语句逻辑挣扎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想找到3个数字之间的最大公约数。我认为我的逻辑是如何做到这一点pretty的声音和我目前没有得到正确的输出。

So I am trying to find the greatest common denominator between 3 numbers. I think that my logic is pretty sound on how to do this and I am currently not getting the correct output.

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。

The three numbers are user inputted into $t0, $t1, and $t2.

推荐答案

您的逻辑是合理的,但你的DIV指令不正确。反转所有三个参数。例如,你在做 S1 = S0%T0 ,你想 S1 = T0%S0

Your logic is sound but your div instructions are incorrect. Reverse the arguments on all three. For example, you're doing s1 = s0 % t0 and you want s1 = t0 % s0

警告:你不能MFLO / MFHI后两个指令中的乘法/除法做,所以你需要在这里和那里添加一个NOP。请参见 http://chortle.ccsu.edu/assemblytutorial/Chapter-14/ass14_5。 HTML 尤其是你的div在IF2 / IF3通过案例违反本在秋季。

WARNING: You can't do multiply/divide within two instructions after mflo/mf so you need to add a nop here and there. See http://chortle.ccsu.edu/assemblytutorial/Chapter-14/ass14_5.html In particular, your div's at if2/if3 violate this in the fall through case.

就个人而言,我会通过后的的MFHI改变它的而不是解决这个问题的的股利。海事组织,因为限制来自MFHI [不div的],所以补偿与它相关联的那干净。而且,对于规律性的缘故,我把它放在三个MFHI的即使一个实际上并不需要它。

Personally, I'd fix this by changing it after the mfhi rather than before the div. IMO, that's cleaner because the restriction comes from mfhi [not div], so associate the compensation with it. And, for the sake of regularity, I'd put it on all three mfhi's even though one doesn't actually need it.

修改

    mfhi ...
    bne ...

ifX:
    div ...

进入:

    mfhi ...
    nop
    bne ...

ifX:
    div ...

只是为了好玩,这里是你的程序翻译回C:

Just for fun, here's your program translated back into 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;
}

这篇关于在if语句逻辑挣扎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆