我正在编写一个MIPS程序,用for-循环来计算从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 -程序完成运行
发布于 2017-05-09 20:18:31
使用1启动t0变量,然后在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了
https://stackoverflow.com/questions/43878951
复制相似问题