You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现含加减号的二项式展开及现有Fortran代码问题修复

二项式展开实现方法与代码修正

二项式带加减号的展开可以直接用二项式定理实现:对$(a+b)n$,展开式为$\sum_{k=0}n C(n,k) a{n-k}bk$;如果是$(a-b)n$,只需要将对应项的系数乘以$(-1)k$即可。

你提供的代码运行结果异常,主要是以下几个问题导致的:

  • 输出数字转字符串时用了i10格式,会生成10位宽度、带大量前置空格的字符串,拼接后格式完全混乱
  • 没有做显示优化:系数为1时不需要额外打印1、变量幂次为1时不需要打印^1、幂次为0时对应变量可以省略
  • 没有处理项之间的运算符拼接,所有项直接连续输出
  • 没有适配减号二项式的符号逻辑

修正后的可运行代码

program binom
implicit none
integer :: nth = 5, i, pow1, pow2, comb, sign
character(:), allocatable :: term, full_exp
character(10) :: strpow1, strpow2, comb_str
character(1) :: var1='x', var2='y', op = '+' ! 要展开减号的话把op改成'-'即可

full_exp = ""
do i=0, nth
    pow1 = nth - i
    pow2 = i
    comb = cnr(nth,i)
    ! 处理减号情况的符号
    if (op == '-' .and. mod(i,2) == 1) then
        sign = -1
    else
        sign = 1
    end if
    comb = comb * sign

    ! 拼接当前项
    term = ""
    ! 处理系数
    if (abs(comb) /= 1 .or. (pow1 == 0 .and. pow2 == 0)) then
        write(comb_str,'(i0)') abs(comb)
        term = term // trim(adjustl(comb_str))
    end if
    ! 处理第一个变量
    if (pow1 > 0) then
        term = term // var1
        if (pow1 > 1) then
            write(strpow1,'(i0)') pow1
            term = term // "^" // trim(adjustl(strpow1))
        end if
    end if
    ! 处理第二个变量
    if (pow2 > 0) then
        term = term // var2
        if (pow2 > 1) then
            write(strpow2,'(i0)') pow2
            term = term // "^" // trim(adjustl(strpow2))
        end if
    end if

    ! 拼接运算符和当前项到完整表达式
    if (i == 0) then
        if (comb < 0) then
            full_exp = full_exp // "-" // term
        else
            full_exp = full_exp // term
        end if
    else
        if (comb < 0) then
            full_exp = full_exp // " - " // term
        else
            full_exp = full_exp // " + " // term
        end if
    end if
end do

! 输出结果
write(*,'(a,"^",i0," = ",a)') "("//var1//op//var2//")", nth, full_exp

contains
  integer function cnr(n,r)     
    implicit none
    integer, intent(in) :: n,r   
    integer :: i, ans            
    integer :: large, small    

    if ((n-r) > r) then
       large = n - r
       small = r
    else
       large = r
       small = n - r
    end if

    ans = 1
   
    do i = large+1, n
       ans = ans*i
    end do

    do i = 2, small
       ans = ans/i
    end do

    cnr = ans
  end function cnr
 
end program binom

运行效果

当设置nth=5, op='+'时,输出为:
(x+y)^5 = x^5 + 5x^4y + 10x^3y^2 + 10x^2y^3 + 5xy^4 + y^5
当设置nth=5, op='-'时,输出为:
(x-y)^5 = x^5 - 5x^4y + 10x^3y^2 - 10x^2y^3 + 5xy^4 - y^5

内容的提问来源于stack exchange,提问作者LDLD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:54:05