Master
Master

Reputation: 59

Convert a REAL output into INTEGER

PROGRAM ONE
IMPLICIT NONE

REAL::num1,num2,num3

READ(*,*)num1,num2
num3=num1+num2
WRITE(*,*)num3

STOP
END PROGRAM ONE

The WRITE statement displays a real number for "num3". What do I do so that it displays an integer value and I am not allowed to change it to integer in the declaration.

Upvotes: 1

Views: 18052

Answers (1)

Wildcat
Wildcat

Reputation: 8870

A real number can be converted to an integer one using the int intrinsic function.

program one

  implicit none

  real :: num1, num2, num3

  read (*, *) num1, num2
  num3 = num1 + num2
  write (*, *) int(num3)

end program one

Note that int function simply truncates its real argument. More precisely, int(a) when a is of type real is calculated as follows:

  • if |a| < 1, int(a) has the value 0;
  • if |a| >= 1, int(a) is the integer whose magnitude is the largest integer that does not exceed the magnitude of a and whose sign is the same as the sign of a.

If this is not what you need, consider using ceiling or floor or nint intrinsic instead. The first one returns the least integer greater than or equal to its real argument, the second returns the greatest integer less than or equal to it, while the third - the nearest integer.

Upvotes: 6

Related Questions