[latex]使用algorithm包来编写伪代码

    xiaoxiao2021-03-25  157

    1)首先在导言区加入语句:

    \usepackage{algorithm} \usepackage{algorithmic} 2)

    \begin{algorithm}[!h] \caption{PARTITION$(A,p,r)$}%算法标题 \begin{algorithmic}[1]%一行一个标行号 \STATE $i=p$ \FOR{$j=p$ to $r$} \IF{$A[j]<=0$} \STATE $swap(A[i],A[j])$ \STATE $i=i+1$ \ENDIF \ENDFOR \end{algorithmic} \end{algorithm}

    效果如下图

    algorithmic和algorithmicx

    介绍下algorithmic和algorithmicx,这两个包很像,很多命令都是一样的,只是algorithmic的命令都是大写,algorithmicx的命令都是首字母大写,其他小写(EndFor两个大写)。下面是algorithmic的基本命令

    \STATE <text>

    \IF{<condition>} \STATE{<text>} \ENDIF

    \FOR{<condition>} \STATE{<text>} \ENDFOR

    \FOR{<condition> \TO <condition> } \STATE{<text>} \ENDFOR

    \FORALL{<condition>} \STATE{<text>} \ENDFOR

    \WHILE{<condition>} \STATE{<text>} \ENDWHILE

    \REPEAT \STATE{<text>} \UNTIL{<condition>}

    \LOOP \STATE{<text>} \ENDLOOP

    \REQUIRE <text>

    \ENSURE <text>

    \RETURN <text>

    \PRINT <text>

    \COMMENT{<text>}

    \AND\OR\XOR\NOT\TO\TRUE\FALSE

    对比看一下,下面是algorithmicx包的基本命令

    \State <text>

    \If{<condition>} <text> \EndIf

    \If{<condition>} <text> \Else <text> \EndIf

    \If{<condition>} <text> \ElsIf{<condition> <text> \Else <text> \EndIf

    \For{<condition>} <text> \EndFor

    \ForAll{<condition><text> \EndFor

    \While{<condition>} <text> \EndWhile

    \Repeat <text> \Until{<condition>}

    \Loop <text> \EndLoop

    \Require <text>

    \Ensure <text>

    \Function{<name>}{<params>} <body> \EndFunction

    \State \Return <text>

    \Comment{<text>}

    另外,还有3个修改algorithm标签,require标签,ensure标签显示的三个命令:

    \floatname{algorithm}{算法}

    \renewcommand{\algorithmicrequire}{\textbf{输入:}} 

    \renewcommand{\algorithmicensure}{\textbf{输出:}}

    转载请注明原文地址: https://ju.6miu.com/read-24868.html

    最新回复(0)