LC-3:处理输入值的条件语句实现及非数字输入处理求助
LC-3 Assembly Solution: Validate Numeric Input (0-5) and Output Result
Got it, let's tackle this problem step by step. Below is a complete LC-3 assembly program that handles all your requirements: it uses TRAP x23 (IN) to get user input, rejects non-numeric characters, checks if the input value is between 0 and 5, and outputs "yes" or "error" accordingly.
Complete Code
.ORIG x3000 ; Define string constants with newline for clean output YES_STR .STRINGZ "yes\n" ERROR_STR .STRINGZ "error\n" ; Main program entry MAIN TRAP x23 ; Read single character input, store ASCII in R0 ; Check if input is NOT a digit (ASCII < '0' or > '9') LD R1, ASCII_0 NOT R1, R1 ADD R1, R1, #1 ; R1 = -x30 (two's complement of '0') ADD R2, R0, R1 ; R2 = input ASCII - '0' BRn NON_DIGIT ; If negative, input is less than '0' LD R1, ASCII_9 NOT R1, R1 ADD R1, R1, #1 ; R1 = -x39 (two's complement of '9') ADD R2, R0, R1 ; R2 = input ASCII - '9' BRp NON_DIGIT ; If positive, input is greater than '9' ; Convert ASCII digit to numeric value (0-9) LD R1, ASCII_0 SUB R0, R0, R1 ; R0 now holds the numeric value (0-9) ; Check if value exceeds 5 LD R1, MAX_VALUE NOT R1, R1 ADD R1, R1, #1 ; R1 = -5 ADD R2, R0, R1 ; R2 = value - 5 BRp OUTPUT_ERROR ; If positive, value > 5 ; Valid input (0-5): output "yes" LEA R0, YES_STR TRAP x22 BR END_PROGRAM NON_DIGIT OUTPUT_ERROR ; Invalid input: output "error" LEA R0, ERROR_STR TRAP x22 END_PROGRAM TRAP x25 ; Halt the program ; Data constants ASCII_0 .FILL x30 ; ASCII value of '0' ASCII_9 .FILL x39 ; ASCII value of '9' MAX_VALUE .FILL #5 ; Upper limit for valid input .END
Key Explanations
Let's walk through how each part works to make sure you understand:
String Setup
.STRINGZcreates null-terminated strings (automatically addsx00at the end), which is required forTRAP x22(PUTS) to know when to stop printing. The\nadds a newline for readability.
Input Handling
TRAP x23grabs a single character from the keyboard and stores its ASCII code in R0.
Non-Numeric Check
- We use two's complement subtraction to compare the input ASCII value against '0' and '9'. If the input is outside this range, we jump straight to the error output.
ASCII to Numeric Conversion
- Subtracting the ASCII value of '0' (
x30) from the input character converts '0' → 0, '1' → 1, ..., '9' → 9. This lets us work with the actual numeric value instead of ASCII codes.
- Subtracting the ASCII value of '0' (
Range Validation
- We check if the numeric value is greater than 5 using two's complement subtraction. If it is, we output an error; otherwise, we output "yes".
Output Logic
LEA R0, STRINGloads the memory address of our string into R0.TRAP x22(PUTS) then prints the entire string starting at that address until it hits the null terminator.
内容的提问来源于stack exchange,提问作者Hexedecimal
相关产品推荐
相关产品推荐

