首先,我通过输入一个C代码来开始这项工作,该代码用正数表示二进制1的数量。我发现首先键入C代码然后尝试转换它更容易。我的C代码如下:
#include <stdio.h>
int main(void)
{
int num;
int remainder;
int one_count=0;
int input_num;
printf("Please enter a positive integer: ");
scanf("%d",&num);
input_num = num;
while (num > 0)
{
remainder = num % 2;
if(remainder == 1)
{
one_count++;
}
printf("%d\n",num);
num = num/2;
}
printf("The number of 1's in %d",input_num);
printf(" is %d\n.",one_count);
return 0;
}
现在,我尝试将其转换为MIPS而不使用指针,但即使我认为我的逻辑是正确的,我仍然会得到零作为答案。我几乎只是在C代码中走下线并试图将其转换为MIPS。我想使用$ sp,但是现在我只是想让它计算正确的数字然后我会尝试实现堆栈。我对MIPS代码的尝试如下:
.data
Prompt1:.asciiz "Please enter a positive integer: "
Prompt2:.asciiz "in "
Prompt3:.asciiz " is "
Result: .asciiz "The number of 1's "
.text
main:
li $v0,4
la $a0, Prompt1
syscall
#get user entered number
li $v0,5
syscall
move $s0,$v0
move $s1,$v0
li $v0,4
la $a0, Result
syscall
li $v0,4
la $a0, Prompt2
syscall
move $a0,$s1
li $v0,1
syscall
li $v0,4
la $a0, Prompt3
syscall
move $a0,$t4
li $v0,1
syscall
onecount:
li $t5,1 #to set remainder equal to 1
li $t2,2 # to divide num by two
ble $s1,$0,exit #if $s1(num <=0), jump to exit
rem $s2, $s0,$t2 # hold modulus in $s2
bnez $s2, increment #if ($s2(remainder) != 0), jump to increment and do . # one_count++
div $s1,$t2 # num = num /2
increment:
addi $t4,$t4,1 # one_count++ to count number of 1's in $t4
j onecount #jump back to one count until num equal to zero
exit:
li $v0,10
syscall
现在,所有这些输出都给我零,它不断运行。我相信我正确设置了C代码的设置方式,但显然没有。如果有人知道我哪里出错了,任何帮助都会很棒。