[英]How do you add more than one condition to a loop in MIPS assembly language?
我目前正在研究匯編代碼的作業問題,該問題要求我們檢查數字是偶數還是奇數。 我正在考慮制作一個 if/else 循環,將給定的數字減去 2,直到數字等於 1 或 0,然后檢查它是哪一個,以便它可以告訴您數字是奇數還是偶數(即使是 0,奇數如果 1)。 但是,我遇到的一個問題是我不知道如何添加一個條件來檢查數字是 1 還是 0。此外,我不確定我是否正確跳轉到每個循環,以及編寫代碼,以文本形式告訴用戶該數字是偶數還是奇數。 這是我目前正在考慮的代碼:
addi s0,0,x #x is substituted with whatever number the user wants to check
addi s1,0,2
addi s2,0,0
addi s3,0,0
bne s0, s2,else OR s0, s3,else #Here, I want the code to check if s0 equals s2 or s3. If so,
#I want itt to jump to a second if statement that will tell you
#if the number is even or odd. If it is not, I want it to jump
#a loop that subtracts by 2 again.
else:
sub s0, s0, s1 # Here I'm pretty sure I have my subtraction right, but how do
# I jump back to the for loop to check if it is 1 or 0 again?
如果要保持相同的邏輯來檢查數字是偶數還是奇數,可以使用以下代碼,其中使用了兩個 beq 語句(檢查了兩個條件)。 基本上,程序將從用戶那里輸入一個數字。 它將不斷從數字中減去 2,直到達到 1 或 0。 如果達到 1,則數字為奇數。 如果達到 0,則數字為偶數。
.data
prompt: .asciiz "Enter the number : "
even: .asciiz "The given number is even "
odd: .asciiz "The given number is odd "
.text
.globl main
main:
li $s1, 1
li $s2, 0
li $s3, 2
li $v0, 4
la $a0, prompt #prompt for the number
syscall
li $v0, 5
syscall
move $t1, $v0 #read number from console and store in $t1
check:
beq $t1, $s1, odd1 #if the number is 1, go to odd
beq $t1, $s3, even1 #if the number is 0, go to even
sub $t1, $t1, $s3 # else subtract 2 from the number
j check #loop
odd1:
li $v0, 4
la $a0, odd #print newline string # printing the number is odd
syscall
j exit
even1:
li $v0, 4
la $a0,even #print newline string # printing the number is even
syscall
exit:
li $v0, 10
syscall
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.