我已经尝试更改此代码的大部分内容,但我不断收到无休止的算术溢出警告或“数据/堆栈中的错误地址”错误。我似乎无法正确理解它!欢迎任何见解!我正在尝试实现一个数独板,这些是该函数的说明:给定一个指向数独板的指针,该函数应该返回一个整数,指示板上有多少个单元格已被解决。董事会的状态不应被修改。每个数独单元总共占用十个字节。每个cell占用10字节,整块板占用810字节内存。
有什么见解吗?
# a0: pointer to board
# v0: number of solved cells
count_solved_cells:
li $v0, 0 # Initialize count to 0
la $s0, board # Load the address of the board to $s0
li $t0, 81 # Initialize loop counter
count_cells_loop:
jal is_cell_solved # Check if the current cell is solved
addi $v0, $v0, 1 # Increment count regardless of cell status
addi $s0, $s0, 10 # Move to the next cell (each cell is 10 bytes)
addi $t0, $t0, -1 # Decrement loop counter
bnez $t0, count_cells_loop # If not reached the end of the board, continue the loop
jr $ra
循环中似乎存在问题,无论单元格状态如何,您都会增加计数。仅当单元格已解决时才应增加计数。另外,您需要正确处理 is_cell_solved 函数的返回值。
这是代码的修改版本:
# a0: pointer to board
# v0: number of solved cells
count_solved_cells:
li $v0, 0 # Initialize count to 0
la $s0, board # Load the address of the board to $s0
li $t0, 81 # Initialize loop counter
count_cells_loop:
jal is_cell_solved # Check if the current cell is solved
beq $v0, $zero, not_solved # If the cell is not solved, jump to not_solved
addi $v0, $v0, 1 # Increment count only if the cell is solved
not_solved:
addi $s0, $s0, 10 # Move to the next cell (each cell is 10 bytes)
addi $t0, $t0, -1 # Decrement loop counter
bnez $t0, count_cells_loop # If not reached the end of the board, continue the loop
jr $ra
此修改包括一个分支(not_solved),用于在单元格未解决时跳过计数的增量。确保 is_cell_solved 函数正确返回一个值,指示单元格是否已求解。