二分法的判断条件弄错了。
(1) 若f(c)=0,则c就是函数的零点;
(2) 若f(a)·f(c)<0,则令b=c;
(3) 若f(c)·f(b)<0,则令a=c.
[Fortran] 纯文本查看 复制代码 module NUMERTICAL
implicit none
real, parameter :: zero = 0.00001
contains
real function bisect(A,B) result(C)!这是声明bisect返回值为一个浮点数
real A,B,FA,FB,FC
C=(A+B)/2.0
FC=func(C)
do while (abs(fc)> zero)
FA = func(A)
FB = func(B)
if(FA*FC < 0)then !//这里注意
B=C
else if( fc*fb < 0 ) then !//这里注意
A=C
end if
C=(A+B)/2.0
FC = FUNC(C)
end do
end function bisect
real function func(X)
real X
func = (X+3)*(X-3)
end function func
end module NUMERTICAL
program main
use NUMERTICAL
implicit none
real A,B
do
write(*,*) '输入两个猜测值'
read(*,*)A,B
if(func(A)*func(B)<0) exit
write(*,*) "不正确的猜测"
end do
write(*,"('x=',F6.3)") bisect(A,B)
end program main |