我在使用fortran来计算e ^ x inside和interval [b.a]的积分时遇到了一些麻烦。
我认为我在funcion调用中做错了。谢谢你的帮助。
program trapezium
implicit none
integer :: i, n, b, a
real :: sumation, mean, deltax, f(i), integral
! The value of the integral using the trapezium rule can be found using
! integral = (b - a)*((f(a) +f(b))/2 + sumation_1_n-1 )/n
write(*,*) "type the limits b, a and the number of intervals"
read *, b, a, n
deltax = (b - a)/n
mean = (f(a) + f(b))/2
sumation = 0
do i = 1, n-1
sumation = sumation + f(i)
end do
integral = deltax*(mean + sumation)
write (*,*) "the value of the integral using the trapezoidal method is", integral
end program
function f(x)
real :: f(x)
integer :: x
f(x) = EXP(x)
end function
答案 0 :(得分:2)
您的代码存在一些问题:
f
是一个函数,但同时您定义了一个数组f(i)
real :: f(i)
仅对常量i
exp()
需要real
变量,而不是整数1/2 = 0
而非0.5
!然而(这不会试图解决数学问题 - 请参阅我的评论):
module functions
contains
function f(x)
implicit none
real :: f
integer,intent(in) :: x
f = EXP(real(x))
end function
end module
program trapezium
use functions
implicit none
integer :: i, n, b, a
real :: sumation, mean, deltax, integral
! The value of the integral using the trapezium rule can be found using
! integral = (b - a)*((f(a) +f(b))/2 + sumation_1_n-1 )/n
write(*,*) "type the limits b, a and the number of intervals"
read *, b, a, n
deltax = real(b - a)/real(n)
mean = (f(a) + f(b))/2
sumation = 0
do i = 1, n-1
sumation = sumation + f(i)
end do
integral = deltax*(mean + sumation)
write (*,*) "the value of the integral using the trapezoidal method is", integral
end program
请注意,使用模块可以使编译器检查函数的参数。此外,您无需在主程序中定义函数的返回值。