实验要求
用AT&T汇编语言编写一程序求一组数(12,4,6,7,80,34,54,46,3,23)最小值和均值,并将在屏幕上输出。
实验过程
流程图:
实验代码:
.section .data
divisor:
.int 10 #个数
array:
.int 12,4,6,7,80,34,54,46,3,23
output:
.ascii "The smallest number is %d, and the average is %d\n"
.section .text
.globl _start
_start:
movl $0,%edi #作为下标
movl array(,%edi,4),%eax #根据索引取值
movl %eax,%ebx #ebx作为temp值
movl %eax,%ecx #求和
change_loop:
cmpl $9,%edi #下标是否已经到了数组的结尾
je EXIT
addl $1,%edi #下标加一,用incl %edi也可以
movl array(,%edi,4),%eax #eax作为根据索引得到的值
addl %eax,%ecx
cmpl %eax,%ebx
jle change_loop #temp<索引值
movl %eax,%ebx #更新temp
jmp change_loop
EXIT:
movl %ecx,%eax #规定被除数为eax,除数为divisor,商放在eax,余数放在edx
movl $0,%edx #没有这行的话,edx是一个随机数,会溢出
divl divisor
pushl %eax
pushl %ebx #第一个参数,最靠近句子
pushl $output
call printf
pushl $0 #一定要有
call exit
编译及链接文件:
在linux系统终端输入编译和链接命令,最终生成可执行文件hw1。
-dynamic-linker /lib/ld-linux.so.2指定c语言的动态链接库。
-lc 使用gnu连接器的-l 参数是为了链接libc.so文件,-c是指定库名称。
结果:
根据题目给出的数据,算出最小值为3,平均数取整后为26,结果正确。