2013-10-18 87 views
0

我必須寫在Fortran語言的腳本返回牛頓二項式的結果: for a, b and n given.寫牛頓二項式在FORTRAN90

的問題是,我不能使用功能或子程序。

直到現在我寫的代碼組合:

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的變量。

回答

0

也許不是最快的解決方案,但很短:

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