Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29275 Discussions

doing a recursive function, can't seem to return an integer

javert8817
Beginner
550 Views

I have the following code, but it is only returning a real. Even though in the function (in this case, fib_result is integer 8, when it gets back to the main program it a bizarre real #. How can i return an integer?

RECURSIVE FUNCTION FIB (n) RESULT (fib_result)

INTEGER :: fib_result

If (n <= 2) then

fib_result = 1

else

fib_result = FIB(n-1) + FIB (n -2)

endif

END FUNCTION

PROGRAM FibRepeat

REAL :: elapsed_time, start, finish

INTEGER :: num, theresult

num = 6

write (6,11) "Final fibonacci value for input of ", num ," is ", FIB(num)

11 FORMAT (1x, A40, 2X, I3, 2x, A4, I9)

END PROGRAM FibRepeat

0 Kudos
2 Replies
Steven_L_Intel1
Employee
550 Views

You need to declare FIB as INTEGER in the main program. Implicitly, it is REAL because the name starts with F (A-H, O-Z). Since FIB is not a contained procedure nor from a module, the compiler doesn't know that you wrote it as INTEGER.

FWIW, if you built this in Intel Visual Fortran in Visual Studio, you should have seen:

t.f90(33): error #7977: The type of the function reference does not match the type of the function definition. [FIB]
write (6,11) "Final fibonacci value for input of ", num ," is ", FIB(num)
-----------------------------------------------------------------^

0 Kudos
gib
New Contributor II
550 Views
Also you should really declare argument n in FIB(n) as integer.
0 Kudos
Reply