1
int X = 0;
int Y = 1;
while(X <= 10 ){
    if(X%2 == 0)
        Y = Y * X;
    else 
        Y++;

    X++;
}
cout << "Y is: " << Y;

这就是我的 Easy68k 代码。

ORG    $1000
START:                  ; first instruction of program

MOVE.W  #0,D1           ;PUT 0 IN D1 (X)
MOVE.W  #1,D2           ;PUT 1 IN D2 (Y)

LOOP CLR.W   D3        ;Find the remainder
     MOVE.W  D1,D3
     DIVU    #2,D3
     SWAP    D3

     CMP     #0,D3      ;Compare remainder with 0
     BEQ     EQUAL      ;If equal, then go to equal

     ADD.W   #1,D2      ;Y++
     ADD.W   #1,D1      ;X++

     CMP     #11,D1     ;Compare D1 with 11
     BEQ     DONE       ;If D1 equals 11, break loop.      
     BRA     LOOP


EQUAL MULU.W  D1,D2     ;Multiply D1 and D2 and store it in D2
      ADD.W   #1,D1     ;X++
      CMP     #11,D1    ;Compare D1 with 11
      BEQ     DONE      ;If D1 equals 11, break loop. 
      BRA     LOOP


DONE LEA MESSAGE,A1
     MOVE.W #14,D0
     TRAP #15

     MOVE.W  D2,D1

     MOVE.W #3,D0
     TRAP #15


    SIMHALT             ; halt simulator

MESSAGE DC.W    'Y is: ',0


    END    START        ; last line of source

我不确定我的代码有什么不正确的地方,但我觉得这是循环部分开头的问题。我已经按照代码进行了操作,但我仍然无法弄清楚哪里出了问题。当我运行它时,它输出 Y 是:10。D1 和 D2 也是 A 或 10。任何帮助表示赞赏。

4

3 回答 3

1

在进行除法和交换之后,您仍然拥有除法的结果和余数d3。这意味着它永远不会为零,并且比较总是错误的。您需要将上部归零或使用仅使用下部and的 form.of。cmp

请注意:当您对 2 的幂进行取余时,您也可以跳过除法并and直接使用值减一。在这种情况下,除以 2 的余数and与值 1 相同。

于 2016-04-05T05:11:36.913 回答
0

与其使用divu更有效和更快的机制来执行与 x%2 相同的操作,不如简单地检查位 0 的状态。这也会产生更少的代码。这显然只适用于 2 的 mod,任何其他值都需要另一种方法(甚至可能是可怕的鸿沟:))

将现有代码更改为阅读(为简洁起见):

LOOP CLR.W   D3        ;Find the remainder
     MOVE.W  D1,D3
     btst    #0,d3     ; Test bit 0
     BEQ     EQUAL      ;If equal, then go to equal
     ...

执行起来会明显更快(在真实硬件上)..您可能不会注意到:)

这是有效的,因为 mod 2 本质上会告诉您一个数字是偶数还是奇数,这可以通过简单地查看是否设置了位 0 来非常便宜地完成

HTH

于 2016-04-05T20:20:38.650 回答
0

Answering on 'what is incorrect':

LOOP CLR.W   D3        ;Find the remainder
     MOVE.W  D1,D3
     DIVU    #2,D3

divu.w and divs.w commands on 68000 take full 32-bit word from second argument and divide it by 16-bit word specified in first argument. Your code doesn't bother to clear high 16 bits of d3 before division. So the change is obvious:

LOOP CLR.L   D3        ;Find the remainder
     ;all the same from here on
于 2016-04-06T14:59:14.103 回答