我整天都在尝试设置必要的命令来代表哈吉斯使用 Latex 中的包创建伪代码格式algorithmicx
。我已经设法创建了我正在描述的简单算法所需的命令,但我无法使缩进正确显示。
在我的主文档中,我定义了以下新命令及其下面的算法:
\documentclass{report}
\usepackage{algpseudocode}
\algnewcommand\algorithmicset{\textbf{SET}}
\algnewcommand\algorithmicto{\textbf{TO}}
\algnewcommand\SET[2]{\item\algorithmicset\ #1 \algorithmicto\ #2}
\algnewcommand\algorithmicreceive{\textbf{RECEIVE}}
\algnewcommand\algorithmicfromkeyboard{\textbf{FROM KEYBOARD}}
\algnewcommand\RECEIVE[1]{\item\algorithmicreceive\ #1 \algorithmicfromkeyboard}
\algnewcommand\algorithmicsend{\textbf{SEND}}
\algnewcommand\algorithmictodisplay{\textbf{TO DISPLAY}}
\algnewcommand\SEND[1]{\item\algorithmicsend\ #1 \algorithmictodisplay}
\algrenewcommand\algorithmicwhile{\textbf{WHILE}}
\algrenewcommand\algorithmicend{\textbf{END}}
\algrenewcommand\algorithmicdo{\textbf{DO}}
\algrenewcommand\algorithmicif{\textbf{IF}}
\algrenewcommand\algorithmicthen{\textbf{THEN}}
\begin{document}
\begin{algorithm}[H]
\caption{Hello world}
\begin{algorithmic}[1]
\SET{$number$}{$0$}
\While{$number \neq -1$}
\SEND{$"Please\ enter\ the\ next\ number\ (-1\ to\ end):\ "$}
\RECEIVE{$number$}
\If{$number \neq -1$}
\SET{$number$}{$total\ +\ number$}
\EndIf
\EndWhile
\SEND{$total$}
\end{algorithmic}
\end{algorithm}
\end{document}
当我创建 PDF 时,我得到以下信息:
我创建的命令有问题,或者我需要做其他我不知道的事情。我搜索了一段时间却没有成功,如果能帮助解决这个问题我将不胜感激,因为我快要抓狂了!毫无疑问,这是我忽略的明显问题。
答案1
尽管algorithmicx
将算法设置为列表 - 意味着应该\item
作为指令设置命令工作 -\State
是在该级别使用适当缩进的首选设置机制:
\documentclass{article}
\usepackage{algpseudocode}
\algnewcommand\algorithmicset{\textbf{SET}}
\algnewcommand\algorithmicto{\textbf{TO}}
\algnewcommand\SET[2]{\State\algorithmicset\ #1 \algorithmicto\ #2}
\algnewcommand\algorithmicreceive{\textbf{RECEIVE}}
\algnewcommand\algorithmicfromkeyboard{\textbf{FROM KEYBOARD}}
\algnewcommand\RECEIVE[1]{\State\algorithmicreceive\ #1 \algorithmicfromkeyboard}
\algnewcommand\algorithmicsend{\textbf{SEND}}
\algnewcommand\algorithmictodisplay{\textbf{TO DISPLAY}}
\algnewcommand\SEND[1]{\State\algorithmicsend\ #1 \algorithmictodisplay}
\algrenewcommand\algorithmicwhile{\textbf{WHILE}}
\algrenewcommand\algorithmicend{\textbf{END}}
\algrenewcommand\algorithmicdo{\textbf{DO}}
\algrenewcommand\algorithmicif{\textbf{IF}}
\algrenewcommand\algorithmicthen{\textbf{THEN}}
\begin{document}
\begin{algorithmic}[1]
\SET{$number$}{$0$}
\While{$number \neq -1$}
\SEND{$"Please\ enter\ the\ next\ number\ (-1\ to\ end):\ "$}
\RECEIVE{$number$}
\If{$number \neq -1$}
\SET{$number$}{$total\ +\ number$}
\EndIf
\EndWhile
\SEND{$total$}
\end{algorithmic}
\end{document}
您会注意到所有\item
s 都改为\State
s。