Wei
Wei

Reputation: 39

How to get right answer when using divide operator

I used fortran to write the following codes:

implicit none
real a,b
integer c
a=0.04
b=0.001
c=a/b

What i got is 39, which I can't figure out why. When I set real to a and b, they are single precision, which means it is accurate enough for this operation to get a right answer of 40. Anyone can explain?

Upvotes: 1

Views: 73

Answers (1)

francescalus
francescalus

Reputation: 32396

For c an integer (of default kind) the assignment c=a/b is equivalent to c=INT(a/b). INT is such that a real number ever so slightly smaller than 40 is mapped to 39.

What do you see with

print *, 0.04, 0.001, 0.04/0.001, INT(0.04/0.001)

? If you really want to see 40, then consider NINT, after reading the popular link.

Upvotes: 1

Related Questions