算法中的单行 while 循环

算法中的单行 while 循环

我正在使用 Algorithm2E,我发现自己处于一种想要表达的情况while(!condition);,但似乎无法在一行中做到这一点。这是我得到的最接近的:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[linesnumbered, ruled]{algorithm2e}
\begin{document}

\begin{algorithm}[H]
\SetKwFunction{KwCrit}{critcalSection}
\SetKwFunction{Kwtas}{test-and-set}
\While{$\Kwtas(r) = 1$}{ }
\KwCrit()\\
$r \gets 0$\\
\caption{Pseudocode of test-and-set usage}
\end{algorithm}

\end{document}

但是这只包含一行,一行只包含结尾。它表达了我想要的,但看起来相当混乱。我怎样才能在一行中表达这一点?

答案1

对于每个将内容放在多行的代码结构\<code>,都有一个\l<code>将内容放在一行的伴随。您还可以使用以下方法定义自己的\WHILE(和伴随的\lWHILE\SetKwFor{<macro>}{<start cond>}{<end cond>}{<end construct>}

在此处输入图片描述

\documentclass{article}

\usepackage{algorithm2e}

\SetKwFor{WHILE}{while (}{)}{}

\begin{document}

\begin{algorithm}[H]
  \SetKwFunction{KwCrit}{criticalSection}
  \SetKwFunction{Kwtas}{test-and-set}
  \lWhile{$\Kwtas{r} = 1$}{}
  \lWHILE{$\Kwtas{r} = 1$}{}
  \KwCrit{}\;
  $r \gets 0$\;
  \caption{An algorithm}
\end{algorithm}

\end{document}

相关内容