Ashir
Ashir

Reputation: 581

Use the floating point instructions to get results in decimal

Hi I'm coding a small program in MIPS that divide 2 between 9 and show the result.This is the code

li $t1, 2
li $t2, 9
li $v0, 2
div $t0,$t2,$t1
move $a0,$t0
syscall

(this is not the full code, just the section handling division)

So, 2 / 9 is 0.2222222222222222

But when I run it I only get 0.0

How I show the true result (0.2222222222222222)?

I've been said that I'm using integer instead of floating point, that I must use the floating point instructions to get results in decimal. That I should look up the div.x instruction, but div.x is not a recognized operator.

So, I'm pretty much in blank. I don't understand what to do.

Could someone post the code to show the floating point result?

Thanks in advance.

Upvotes: 5

Views: 17811

Answers (4)

Ashir
Ashir

Reputation: 581

Ok, after a long try and mistake the right way to print the true result is:

Set 2 floating points registers using pseudo li.s (Thanks to Paul R for point me in the right direction)

li.s $f1, 2.0
li.s $f2, 9.0

Obviously, prepare to print a float

li $v0, 2

At division instead of div $t0,$t2,$t1 I should use

div.s $f12,$f1,$f2

and instead of move $a0,$t0 I should just

syscall

There is no need to move, div.s prints outs the result at once so there is no real need to move the contents of $f12 into $a0 for print its content.

It's a real shame that mars doesn't implment the pseudo li.s. I had to try this on PCSPIM...

The final code is

.globl main
.text
main:
li.s $f1, 2.0
li.s $f2, 9.0
li $v0, 2
div.s $f12,$f1,$f2
syscall
li $v0, 10
syscall

When you run it you'll get 0.22222222, the true result of dividing 2 between 9.

Upvotes: 10

wallyk
wallyk

Reputation: 57764

Without knowing the full objectives, perhaps it suffices to use a convenient integer shortcut: divide 2 billion by 9 and display that with an artificially inserted decimal point. In C, this would be something like

printf ("0.%d", 2000000000 / 9);

Upvotes: 0

Jens Björnhager
Jens Björnhager

Reputation: 5649

You are doing integer division. Use the floating point instructions to get results in decimal. Look up the div.x instruction.

Upvotes: 0

Paul R
Paul R

Reputation: 212929

It's an integer division instruction, so 2 / 9 = 0 is the correct result. Try e.g. 27 / 9 and you should get a result of 3.

Upvotes: 3

Related Questions