函数声明警告:未设置(1)处的函数'f'的返回值[-Wreturn-type]

问题描述 投票:1回答:1

我的代码可以编译,但是有错误:

Warning: Return value of function ‘f’ at (1) not set [-Wreturn-type].

我用geany。下面是我的代码。

        program ROVNICANEWTON

        implicit none

        integer k
        double precision x0, f, df

        k=0
        x0=2d0

        if (abs(f(x0)) .lt. (0.0000000001)) then
         go to 20
        else
         k=k+1
         x0=x0-f(x0)/df(x0)
         print *, k 
        end if

20     continue    

    open(30, file='NEWTON.txt', status='unknown')
        write(30,*) 'x = ', x0  
    close(30)    
        END PROGRAM

        double precision function f(x)
        implicit none
        double precision, intent(in) :: x

        f(x)=(x**(x**2))-1000

        return
        end function f

        double precision function df(x)
        implicit none
        double precision, intent(in) :: x

        df(x)=2*x**(2+x**2)

        return
        end function df 
fortran gfortran geany
1个回答
2
投票

我认为,这种情况下的错误消息使您误入歧途。这表明您没有为函数创建返回值,而实际上您尝试执行的行在语法上是不正确的。

请记住,每当函数执行时,x将具有特定值,因此返回值f也必须具有特定值:

double precision function f(x)
    implicit none
    double precision, intent(in) :: x
    f = (x**(x**2)) - 1000
end function f

类似地,您需要从(x)行中删除df(x)=2*x**(2+x**2)

在这种情况下,我也不喜欢您使用goto。很多时候,当您想到使用goto时,都有一种更好的,更少打扰的方式。

这是因为goto中断了源代码的流程。这使得它很难遵循。

在这种情况下,您想要的是在满足条件之前执行此操作。有两种方法可以使它更易于阅读:

do
    if (abs(f(x0)) < 1d-10) exit
    k = k + 1
    x0 = x0 - f(x0)/df(x0)
    print *, k
end do

或更确切地说:

do while (abs(f(x0)) >= 1d-10)
    k = k + 1
    x0 = x0 - f(x0)/df(x0)
    print *, k
end do
© www.soinside.com 2019 - 2024. All rights reserved.