用Fortran90编写牛顿二项式
我必须用Fortran编写一个脚本,返回牛顿二项式的结果: 问题是我不能使用函数或子程序 到目前为止,我已经为这些组合编写了代码:用Fortran90编写牛顿二项式,fortran,Fortran,我必须用Fortran编写一个脚本,返回牛顿二项式的结果: 问题是我不能使用函数或子程序 到目前为止,我已经为这些组合编写了代码: if (n==0) then print*, "Cnk=",Cnk else if ((n>=0).and.(k==0)) then print*, "Cnk=",Cnk else do i=1,n,1 aux=aux*i if (k==
if (n==0) then
print*, "Cnk=",Cnk
else if ((n>=0).and.(k==0)) then
print*, "Cnk=",Cnk
else
do i=1,n,1
aux=aux*i
if (k==i) then
factK=aux
end if
if ((n-k)==i) then
factnk=aux
end if
factn=aux
end do
Cnk=factn/(factk*factnk)
print*, "Cnk=",Cnk
end if
在二项式的情况下,k是从0到n的变量。可能不是最快的解决方案,但很短:
program binom
implicit none
integer,parameter :: N=5
integer,parameter :: a=3
integer,parameter :: b=5
integer :: k, i
integer :: coeff, eval, total
total = 0
do i=0,N
coeff = product((/ (k,k=1,n) /)) / product((/ (k,k=1,i),(k,k=1,n-i) /))
eval = coeff * a**(n-i) * b**i
total = total + eval
write(*,*) 'i=',i,'coeff=',coeff, 'eval=',eval
enddo !i
write(*,*) '(a+b)**n=',(a+b)**N,'Total=',total
end program binom
输出:
i= 0 coeff= 1 eval= 243
i= 1 coeff= 5 eval= 2025
i= 2 coeff= 10 eval= 6750
i= 3 coeff= 10 eval= 11250
i= 4 coeff= 5 eval= 9375
i= 5 coeff= 1 eval= 3125
(a+b)**n= 32768 Total= 32768