【问题标题】:Calculating length of sub strings of consecutive characters MIPS计算连续字符MIPS的子串长度
【发布时间】:2014-10-17 19:08:46
【问题描述】:

我正在使用 MIP 编写一个程序,该程序从用户那里获取输入字符串并输出连续相同字符的最长子字符串。我的问题似乎是在程序输出目标字符串之前似乎已经达到了“结束”。任何帮助表示赞赏!

main:
    la $a0,input_msg        # Prompting input from user
    li $v0,4
    syscall

    li $v0, 8               # Reading string and storing in memory 
    la $a0, input_string
    li $a1, 100
    syscall


    li $t0, 0 
    la $t1, input_string            # address of the first element
    lb $a0, ($t1)               # input_string[0] (the first character)

    move $s0, $a0           # current_char=read_char();
    move $s1, $a0           # previous_char = input_string[0];
    move $s2, $a0           # final_char=input_string[0];

    li $s3, 1           # current_num_chars=1;
    li $s4, 1           # final_num_chars=1;


    la $t5, new_line

loop:

    addi $t0, $t0, 1        # for(k=1; k<i-1; k++)  {
    add $t1, $t1, $t0       
    lb $t3, ($t1)
    beq $s5, $t3, print_final
    move $s0, $t3           # current_char=input_string[k];

    bne $s0, $s1, else          # if(current_char == previous_char)
    addi $s3, $s3, 1        # current_num_chars++; 

    bge $s3, $s4, increase_final    # if(current_num_chars >= final_num_chars) {    

    move $s1, $s0
    j loop              # else do nothing

increase_final: 

    move $s2, $s0           # final_char=current_char;
    move $s4, $s3           # final_num_chars=current_num_chars; 

    move $s1, $s0
    j loop              # }


else:   
    move $s1, $s0   
    j loop              # else {
                    #   current_num_chars=1;
                    # }
                    # }

print_final:

    la $a0, output_msg
    li $v0, 4
    syscall

    li $t2, 0

print_chars:    

    li $t2, 0           #  for(k=0; k<final_num_chars; k++)  {
    beq $t2, $s3, end

    move $a0, $s2           # print_char(final_char);
    li $v0, 11
    syscall

    j print_chars           # }

end:

    li   $v0, 4           # print_string("\n");
    la   $a0, new_line
    syscall

    li   $v0, 10          # exit()
    syscall

【问题讨论】:

    标签: arrays string assembly mips


    【解决方案1】:

    您的print_chars 循环将$t2(您刚刚设置为0)与$s3 进行比较,以决定是否跳转到结束。因此,它将始终进行相同的比较,并且您的循环将在第一次遇到时退出,或者永远不会结束。

    另外,评论表明您应该与$s4 进行比较,而不是$s3

    【讨论】:

    • 啊当然!我什至没有注意到这一点!谢谢!不幸的是,现在它运行了,但抛出了一个关于 ln58 的错误,这是以loop: addi $t0, $t0, 1 # for(k=1; k&lt;i-1; k++) { add $t1, $t1, $t0 lb $t3, ($t1) beq $s3, $t5, print_chars move $s0, $t3 # current_char=input_string[k]; 开头的部分
    • 原代码已更改,应改为la $s5, new_line,而不是la $s4, new_linebge $t0, $t8, end 替换为beq $s3, $s5, print_chars
    • 除非您可以使用新代码和问题编辑问题,否则请关闭此问题并发布新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多