我想翻译一个计算从1到n之和的java代码到arm程序集,我想知道我是否正确翻译它?
这是我正在翻译的java代码的代码:
int sum = 0 ;
int num = 10;
int count = 1 ;
while ( count <= num )
{
sum += count ;
count++ ;
}
System.out.println(sum);
到目前为止,这是我的手臂汇编代码:
MOV r1, #0 ;store sum
MOV r2, #10 ;number to count to
MOV r3, #1 ;starting count
start_while: ;start while loop
CMP r3, r2 ;while count is less than number
ADD r1, r1, r3 ;add count to sum
ADD r3, r3, #1 ;increment count
BNE start_while ;end while loop
;print sum???
我是否正确翻译了while循环,如何打印总和?对不起我对手臂组装比较陌生,所以我不知道我做得对不对。
答案 0 :(得分:0)
while()通常翻译如下:
_start:
if (!condition) jump to _end
; do stuff inside the while loop
jump to _start
_end:
所以你的循环看起来像这样:
MOV r1, #0 ;store sum
MOV r2, #10 ;number to count to
MOV r3, #1 ;starting count
start_while: ; start while loop
CMP r3, r2 ; jump below while block if while condition is
BGT end_while ; not true anymore ( "<= 10" gets ">10")
ADD r1, r1, r3 ;add count to sum
ADD r3, r3, #1 ;increment count
B start_while ;go on with loop (no condition here)
end_while:
;print sum???