c - 如何计算MIPS中两个值之间的偶数之和?

标签 c loops branch mips

我对如何将 C 代码转换为 MIPS 感到困惑。我似乎对循环感到困惑,我认为我可能使用了错误的命令。我为此编写的 C 代码如下:

int main()
{
   int x, y;
   int sum = 0;
   printf("Please enter values for X and Y:\n ");
   scanf("%d %d",&x,&y);


   if (x > y)
   {
     printf("\n** Error");
     exit(0);
   }
   while (x <= y)
   {
     if (x%2 == 0)
        sum += x;
        x++;
   }
   printf("\nThe sum of the even integers between X and Y is: %d\n\n",sum);

   return 0;
}

我对MIPS翻译的尝试如下:

   .data
 Prompt:   .asciiz   "Please enter values for X and Y:\n"
 Result:   .asciiz   "The sum of the even integers between X and Y is: \n"

    .text
 li $v0,4              #load $v0 with the print_string code.
 la $a0, Prompt        #load $a0 with the message to me displayed
 syscall

 li $v0,5              #load $v0 with the read_int code for X
 syscall
 move $t0,$v0

 li $v0,5              #load $v0 with the read_int code for Y
 syscall
 move $t1, $v0

 while:

   slt $t2, $t1,$t0  #$t1 = y   $t0 = x
   li $t3,2
   div $t2,$t3
   beq $t2,$0,else
     add $s1,$s1,$t0      #s1 = s1 + x
     addi $t0,$t0,1       #x++
   j while

else:
   li $v0,4
   la $a0, Result
   syscall

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

我认为我的错误出在我的 MIPS 代码的循环中。我的结果不断产生零,我认为我的代码正在检查循环,然后跳转到我的 else 语句。

经过进一步的工作,我让它计算所有整数的总和,但我不太确定它为什么这样做。这是我最近的更新:

while:

   sle $t2, $t0,$t1     #$t1 = y   $t0 = x
   li $t3,2        #t3 = 2
   div $t2,$t3       #$t2/2
   beq $t2,$0, else   #if ($t2/2 == 0), jump to the else, otherwise do else
     add $s1,$s1,$t0      #s1 = s1 + x
     addi $t0,$t0,1      #x++
   j while

现在,如果我输入 1 和 5,它会计算 1 和 3,结果是 6,而不仅仅是偶数总和,而本应是 2。

最佳答案

为了回答我自己的问题,主要的困惑在于分支。我现在明白它们的工作原理就像相反的,所以例如,我必须将 while 循环中的“beq”设置为 bnez,这样它就会在 $t2 为 != 0 时进行计算。另一个小修复是在外部添加增量循环的。因此,当 $t2 != 0 时,我跳转到“else”,然后递增以查找下一个数字。但是,如果余数为 0,则执行 sum=sum + x 的数学运算。总之,主要的困惑来自于对分支的相反射(reflection)考。我现在明白了,如果我想说:

同时(a1

我必须把它写成

while:
 bgeu $a1,$a2, done
   addi "whatever"
 b while

done:
      do done stuff

在这种理解之前,我将其写为 ble $a1,$a2,done,但这不是它的键入方式。从逻辑上讲,这表示如果 a1 < a2...但实际上是说如果 a1 < a2,则跳转到“完成”并跳过计算。所以我只能从相反的角度思考。

关于c - 如何计算MIPS中两个值之间的偶数之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42194488/

相关文章:

c - 在 C 中打印列表的元素

核心转储不起作用

javascript - 如何比较和匹配两个不同对象的对象键?

git - 单独的克隆,或单独的分支

intellij-idea - 如何使用 IntelliJ IDEA 检查 CVS 分支 HEAD?

C printf 编译器警告

c - 您打算如何将文件包含在 C 项目中?

loops - 使用嵌套循环的乘法表

c++ - while 循环和 if/else 语句不能正常工作

git - 在 git 中切换分支 - 我什么时候会得到 "You have local changes cannot switch branches."?