汇编语言实验,从键盘输入一组数据,存入一维数组中(要求数组的长度为字,数组必须为字长),统计偶数和奇数的个数并分别显示在屏幕上。
时间: 2023-12-18 18:03:08 浏览: 119
以下是汇编语言实验的代码,使用的汇编语言为x86:
```
section .data
prompt db 'Please input the length of the array: '
prompt_len equ $-prompt
array_prompt db 'Please input the array elements: '
array_prompt_len equ $-array_prompt
even_msg db 'The number of even elements is: '
even_msg_len equ $-even_msg
odd_msg db 'The number of odd elements is: '
odd_msg_len equ $-odd_msg
newline db 10
section .bss
len resw 1
array resw 100
even_count resw 1
odd_count resw 1
section .text
global _start
_start:
; Prompt the user for the length of the array
mov eax, 4
mov ebx, 1
mov ecx, prompt
mov edx, prompt_len
int 80h
; Read in the length of the array from the user
mov eax, 3
mov ebx, 0
mov ecx, len
mov edx, 2
int 80h
; Convert the length from ASCII to integer
mov bx, [len]
sub bx, 30h
mov word [len], bx
; Prompt the user for the array elements
mov eax, 4
mov ebx, 1
mov ecx, array_prompt
mov edx, array_prompt_len
int 80h
; Read in the array elements from the user
mov esi, array
mov ecx, [len]
mov edx, 2
read_loop:
mov eax, 3
mov ebx, 0
mov edi, esi
mov ecx, 1
int 80h
; Convert the element from ASCII to integer
mov bx, [esi]
sub bx, 30h
mov [edi], bx
; Check if the element is even or odd
mov eax, [esi]
and eax, 1
jz even
inc word [odd_count]
jmp next
even:
inc word [even_count]
next:
add esi, 2
loop read_loop
; Display the number of even elements
mov eax, 4
mov ebx, 1
mov ecx, even_msg
mov edx, even_msg_len
int 80h
mov eax, 4
mov ebx, 1
mov ecx, [even_count]
mov edx, 2
int 80h
; Display a newline character
mov eax, 4
mov ebx, 1
mov ecx, newline
mov edx, 1
int 80h
; Display the number of odd elements
mov eax, 4
mov ebx, 1
mov ecx, odd_msg
mov edx, odd_msg_len
int 80h
mov eax, 4
mov ebx, 1
mov ecx, [odd_count]
mov edx, 2
int 80h
; Exit the program
mov eax, 1
xor ebx, ebx
int 80h
```
该程序首先提示用户输入数组的长度,然后读取长度并将其转换为整数。接下来,程序提示用户输入数组元素,并读取数组元素。在读取每个元素时,程序将该元素转换为整数,并检查它是偶数还是奇数。程序使用两个计数器来跟踪偶数和奇数的数量。最后,程序显示偶数和奇数的数量,并退出。
阅读全文