MIPS:查找第k个最大整数

时间:2018-08-01 12:28:04

标签: assembly mips

此代码在某种程度上陷入了获取无限数量输入的循环。 我需要输入有限数量的整数,例如n = 10,然后再输入另一个来自键盘的输入,例如k = 3。然后我必须输出这10个数字中的第3个最大数字。

提示和输出应如下所示:

Enter count: 5
Enter integers: -5
3
12
8
2
Enter k: 2
kth largest is: 8
Enter count: 5
Enter integers: -5
3
12
8
2
Enter k: 6
Error

代码

    .data
    .align 2
    myarray: .space 160
    endline: .asciiz "\n"
    msg: .asciiz "Enter count(number of integers to be input): "
    msg2: .asciiz "Enter integers: "
    msg4: .asciiz "Enter k: "
    msg3: .asciiz "kth largest integer is: "
    msg5: .asciiz "Error"
    msg6: .asciiz "I will do something here"
.text
 main:  


    #show the the msg1
    li $v0,4
    la $a0,msg
    syscall

    #enter the number of integers(n)
    li $v0,5
    syscall
    move $t4,$v0 #value of (n)

    #take input of n numbers
    li $v0,4
    la $a0,msg2
    syscall

    j fun

temp:
    #take input of k
    li $v0,4
    la $a0,msg4
    syscall

    li $v0,5
    syscall
    move $t2,$v0 #value of k

    #if k>n error
    bgt $t2,$t4,showerror       

    #if k<=n do something
    ble $t2,$t4,func

    #end
    li $v0,10  
    syscall

    fun:

    addi $sp,$sp,-4
    #enter the numbers
    li $v0,5 
    syscall

    mul $t4,$t4,4

    beq $t0,$t4,exit #($t0=40 =>exit)

    sw $v0,myarray($t0)

    addi $t0,$t0,4
    addi $sp,$sp,4
    j fun

    exit:
    jr $ra

    showerror:
    li $v0,4
    la $a0,msg5 
    syscall

    func:
    li $v0,5
    la $a0,msg6
    syscall

更新:我已经按照您提到的方式更新了代码,添加了jal,但之前我没有做过尝试。

0 个答案:

没有答案