MEAN、MEDIAN 和 MODE 函数的 MIPS 代码
Posted
技术标签:
【中文标题】MEAN、MEDIAN 和 MODE 函数的 MIPS 代码【英文标题】:MIPS codes for MEAN, MEDIAN & MODE functions 【发布时间】:2021-06-24 00:40:56 【问题描述】:我刚刚开始学习 MIPS。谁能帮我找到数组的均值、中值和众数的代码? TIA。
【问题讨论】:
【参考方案1】:.data
newline: .asciiz "\n"
total: .asciiz "Sum: "
mean: .asciiz "Mean: "
median: .asciiz "Median: "
mode: .asciiz "Mode: "
array: .word 1, 2, 2, 3, 3, 3, 4, 4, 5, 5
.word 5, 5, 5, 5, 6, 6, 6, 7, 8, 8
.word 8, 8, 8, 8, 8, 9, 9, 9, 10, 10
length: .word 30
sum: .word 0
average: .word 0
.text
.globl main
.ent main
main:
#loop through the array to calculate sum
la $t0 array #array's starting address
li $t1 0 #loop index, i=0
lw $t2 length #length
li $t3 0 #initialise sum =0
sumLoop:
lw $t4 ($t0) #get array[i]
add $t3 $t3 $t4 #sum = sum+array[i]
addi $t1 $t1 1 #i = i+1
add $t0 $t0 4 #update array address
blt $t1 $t2 sumLoop
sw $t3 sum #save sum
#printing sum
li $v0,4
la $a0, total
syscall
move $a0 $t3
li $v0 1
syscall
#calculate average
div $t5 $t3 $t2
sw $t5 average
#giving space of a line
li $v0,4
la $a0, newline
syscall
#printing mean statement
li $v0,4
la $a0, mean
syscall
move $a0 $t5
li $v0 1
syscall
#calculating median
la $t0, array
lw $t1, length
li $t3 4
div $t2, $t1, 2 #length / 2
mul $t3, $t3, $t2 #index*4
add $t4, $t0, $t3 #getting address of array[15]
lw $t5, ($t4) #getting value of array[15]
sub $t4, $t4, 4 #getting address of array[14]
lw $t6, ($t4) #getting value of array[14]
add $t7, $t6, $t5 #array[14] + array[15]
div $t8, $t7, 2 #median
#giving space of a line
li $v0,4
la $a0, newline
syscall
#printing median
li $v0,4
la $a0, median
syscall
move $a0 $t8
li $v0 1
syscall
#calculating mode
la $t0 array
li $t1 0 #i=0
lw $t2 length
li $t4, 1
li $t6, 1
li $t7, 0
li $t8, 0 #modeValue
li $t9, 0 #modeCount
Loop:
lw $t5 ($t0) #get array[i]
bne $t4 ,$t5 , if
previous:
addi $t7 $t7 1 #counter++
addi $t1 $t1 1 #i++
add $t0 $t0 4 #next array address
li $t4 ,0
addi $t4 , $t5, 0
blt $t1 $t2 Loop
#giving space of a line
li $v0,4
la $a0, newline
syscall
#printing mode statement
li $v0,4
la $a0, mode
syscall
move $a0 $t8
li $v0 1
syscall
li $v0 10
syscall
.end main
if:
bgt $t7, $t9, update
next:
li $t6 ,0
addi $t6 , $t5, 0
li $t7, 0
j previous
update:
li $t8 ,0
addi $t8 , $t4, 0
li $t9 ,0
addi $t9 , $t7, 0
j next
【讨论】:
代码有效,但当我保持数组长度为 5 时给出错误的中位数 均值的代码是偶数数组长度,因为目前它是中位数 = (array[length/2] + array[length/2 - 1])/2,奇数数组长度就行了到中位数 = 数组[长度/2]以上是关于MEAN、MEDIAN 和 MODE 函数的 MIPS 代码的主要内容,如果未能解决你的问题,请参考以下文章
8InfluxDB常用函数聚合函数,count()函数,DISTINCT()函数,MEAN()函数,MEDIAN()函数,SPREAD()函数,SUM()函数