2017-06-27 29 views
1

我想一個while循環這樣的轉換:while循環與2個條件彙編代碼

i=0; 
while ((s[i]!='t') && (i<=20)) { 
    d[i]=c[i]; 
    i++; 
} 

2個條件彙編代碼。 我該怎麼做?下面是 的版本,同時有1個條件。

################################################# 
# lab3_3a.s     # 
# while loop char!=ASCII 0   # 
################################################# 
    .text  
     .globl __start 
__start:   # execution starts here 

    li $t1,0  # counter for string 
    li $s0,'t'  # chararacter to end copy 
while: lbu $t0,string($t1) # load a character 
    sb $t0,copy($t1) # copy character 
    beq $t0,$s0,end  # if character to end copy then exit loop 
    addi $t1,$t1,1  # increment counter 
    b while   # repeat while loop 
end: li $t2,0 
    sb $t2,copy($t1) # append end character to copied string 
    la $a0,copy  # display copy 
    li $v0,4  
    syscall 
    li $v0,10  # exit 
    syscall   
     .data 
string:  .asciiz "Mary had a little lamb" 
copy:  .space 80 

謝謝你們。

+0

我不會爲你寫代碼,但我可以告訴你在彙編中需要檢查兩次--JNE和JLE。另外,什麼是s,d,c? – EvgenyKolyakov

+0

想怎麼做'if(s [i]!='t'&& i <= 20)i ++'首先然後替換body @EvgenyKolyakov MIPS中沒有'jne'和'jle' –

+2

您應該至少顯示您已經擁有一個條件的代碼。並解釋你對'&&'(假定)短路行爲的理解。 –

回答

1

所以,你已經成功地顛倒了其中一個條件,並用它跳出循環。它發生在你身上,你可以爲另一個人做同樣的事情嗎?

li $t1,0  # counter for string 
    li $s0,'t'  # chararacter to end copy 
    li $s1,20  # count to end copy 
while: lbu $t0,string($t1) # load a character 
    sb $t0,copy($t1) # copy character 
    beq $t0,$s0,end  # if character to end copy then exit loop 
    bgt $t1,$s1,end  # if count exceeds limit then exit loop 
    addi $t1,$t1,1  # increment counter 
    b while   # repeat while loop 
1
i=0; 
while ((s[i]!='t') && (i<=20)) { 
    d[i]=c[i]; 
    i++; 
} 

將包含兩個錯誤,如果s將被定義爲char s[20];,第一(i<=20)將是一個太了。在陣列長度測試中使用<=是非常不尋常的,如果定義了char s[21];,但在源碼20和21中有兩個不同的「幻數」,那麼它仍然是正確的。第二個錯誤是,即使您的長度正確測試時,(s[i]!='t')將在i驗證之前執行,因此在最後一個字符中,您將有超出界限的訪問權限。

反正就是C下用C語言編寫的多一點「組裝式」的方式是這樣的:

i=0; 
while(true) { // Your "b while" is doing this already 
    if (20 < i) break; // test length first, to avoid s[21] (out of bounds) 
    if ('t' == s[i]) break; // test for "terminator" character 
    //^^ Yoda notation, to catch typo like (s[i]='t') as error 
    d[i]=c[i]; 
    ++i; // pre-increment form is more accurate to your intent 
     // As you don't need original value after incrementation 
} 
// breaks will jump here. 

這應該很容易組裝重寫,嘗試...


編輯:您的原始程序集不是「while」,而是「do-while」,即第一個字節的副本將在所有情況下執行,這不是C示例正在做的事情。


edit2:同時當然這個假設你知道布爾邏輯代數,就像每個程序員都必須知道的那樣。即你知道:

!(A && B) <=> (!A) || (!B)