避免將語句與演算法放在同一行

避免將語句與演算法放在同一行

我正在編寫一個簡單的偽代碼,但我遇到了重複..直到塊的問題。基本上發生的情況是,這個循環結束後的 return 語句被渲染在與until子句相同的行上,這很醜陋,但我找不到一種方法將它放在自己的一行上具有正確的縮排

在這裡你可以有一個例子:

\documentclass[a4paper,10pt]{article}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{test di Fermat}\label{alg:test-fermat}
\begin{algorithmic}[1]
\Procedure{testFermat}{$n, prove$}
    \Repeat
        \State{$a \gets$ numero casuale tra 2 e $n-1$}
        \If{$a^n \not\equiv a \bmod n$}
            \Return composto
        \EndIf
        \State{$prove \gets prove - 1$}
    \Until{$prove > 0$}
    \Return forse primo
\EndProcedure
\end{algorithmic}
\end{algorithm}
\end{document}

我嘗試使用 添加換行符\\,但這會破壞縮排。我嘗試過\algorithmicindent手動添加縮進,但這顯示“1.5em”而不是空格。我嘗試在後面添加\State或,但這也會破壞縮排。\Statex\Until

有沒有一種簡單的方法可以將最後一個\Return單獨放在一行上,而不破壞縮排?

順便說一句,這種情況也會發生在 If 區塊內的 return 中,但我更擔心帶有 Until 的區塊,因為 if 區塊中的 return 看起來並不那麼糟糕。

編輯:我讀過問題,但並不能解決問題。

我不想使用varwidth,因為我必須修復直到循環,所以我必須手動管理所有縮排[varwidth在循環中間啟動環境會破壞其他縮排]。

答案1

這也許是一種根據地位而設計的選擇,讓人們可以選擇與\Return其他陳述保持一致還是獨立。要讓它在預設情況下單獨放置,請添加

\algrenewcommand\Return{\State \algorithmicreturn{} }%

到您的文件序言。

在此輸入影像描述

\documentclass[a4paper,10pt]{article}
\usepackage{algorithm}% http://ctan.org/pkg/algorithms
\usepackage[noend]{algpseudocode}% http://ctan.org/pkg/algorithmicx
\algrenewcommand\Return{\State \algorithmicreturn{} }%
\begin{document}
\begin{algorithm}
  \caption{test di Fermat}\label{alg:test-fermat}
  \begin{algorithmic}[1]
    \Procedure{testFermat}{$n, prove$}
      \Repeat
        \State{$a \gets$ numero casuale tra 2 e $n-1$}
        \If{$a^n \not\equiv a \bmod n$}
          \Return composto
        \EndIf
        \State{$prove \gets prove - 1$}
      \Until{$prove > 0$}
      \Return forse primo
    \EndProcedure
  \end{algorithmic}
\end{algorithm}
\end{document}​

答案2

最簡單的解決方案是將 return 語句包裝在State指令中,如下所示:

 \State{\Return{composto}}

相關內容