
在使用 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}