在使用 Latex 语法编写算法时,我遇到了缩进问题,即程序在一个地方开始,在另一个地方结束。部分代码:
\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\makeatletter
\def\BState{\State\hskip-\ALG@thistlm}
\makeatother
\begin{document}
\begin{algorithm}
\caption{Test}\label{euclid}
\begin{algorithmic}[1]
\State $\textit{currentS} \gets \textit{initialS}$
\State $\textit{bestS} \gets \textit{currentS}$
\State $\textit{listTest} \gets \left[ \right]$
\While{$fitness(bestS) < 0$}{
\State $\textit{bestC} \gets \textit{null}$
\For {($\textit{ca} \in \textit{currentS.get})}${
\If{($\neg\textit{listTest.contains(c)})$}{
\EndIf}
\EndFor}
\EndWhile}
\State \Return $\textit{bestSolution}$
\end{algorithmic}
\end{algorithm}
\end{document}
答案1
你误用了该工具:语法\While
是
\While {<condition>}
...
\EndWhile
循环内容周围没有括号。
完整代码(我\State
在内部添加了\If
);还请注意\mathit
优于\textit
。对于空数组,我将其更改\left[\right]
为[\,]
。
\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\makeatletter
\def\BState{\State\hskip-\ALG@thistlm}
\makeatother
\begin{document}
\begin{algorithm}
\caption{Test}\label{euclid}
\begin{algorithmic}[1]
\State $\mathit{currentS} \gets \mathit{initialS}$
\State $\mathit{bestS} \gets \mathit{currentS}$
\State $\mathit{listTest} \gets [\,]$
\While{$\mathit{fitness}(\mathit{bestS}) < 0$}
\State $\mathit{bestC} \gets \mathit{null}$
\For {($\mathit{ca} \in \mathit{currentS.get})}$
\If{($\neg\mathit{listTest.contains(c)})$}
\State do something
\EndIf
\EndFor
\EndWhile
\State \Return $\mathit{bestSolution}$
\end{algorithmic}
\end{algorithm}
\end{document}