使用MIPS中的for循环计算从1到10的所有奇数之和

时间:2017-05-09 20:05:46

标签: for-loop mips

我正在使用for循环编写一个MIPS程序来计算从1到10的所有奇数之和。应该是25,但我得到了48.我不知道错误在哪里。这是我的代码:

################# Pseudocode ##################### 
 i = 1
 n = 10
 sum = 0
   for(i=1; i<=10; i+=2) {
       sum += i;
   }
  printf("The sum of all odd number from 1 to 10 is: %d", sum);
  return 0;

################# Data segment ##################### 
        .data
msg:    .asciiz     "\ncurrent tally: \n"

################# Code segment ##################### 
    .text
    .globl  main

main:
    li      $t0, 1      # temp counter, starts at 1 
    li      $t1, 0      # set to zero, to store sum

add_loop:
    bgt    $t0, 11, end_loop    # break out of loop if counter > 11
    addi    $t0, $t0, 2          # add 2 in $t0 to skip even num
    add     $t1, $t1, $t0        # sum += i

    li      $v0, 4
    la      $a0, msg
    syscall                      # print out user-friendly msg

    li      $v0, 1
    move    $a0, $t1
    syscall                      # print out result from loop

    j       add_loop

end_loop:
    li      $v0, 10              # terminate program run and
    syscall                      # exit 

输出:     目前的记录:     3     目前的记录:     8     目前的记录:     15     目前的记录:     24     目前的记录:     35     目前的记录:     48      - 程序运行完毕 -

1 个答案:

答案 0 :(得分:2)

您使用1开始t0 var,然后在add $t1, $t1, $t0之前添加2,因此要归待为t1的第一个值为3,您缺少1。

然后,由于休息条件为>11,因此11也总和为t1。 最后,你也在其他地方添加了+13(也许它在打破循环之前进行了最后一次迭代?),所以-1 + 11 + 13给出了25和48之间的差异23。

所以可能会做得更好

add_loop:
    bgt    $t0, 9, end_loop    # break out of loop if counter > 9 (so 9 is counted as well!)
    add     $t1, $t1, $t0        # sum += i
    addi    $t0, $t0, 2          # add 2 in $t0 to skip even num

由于您已经从t0=1

开始