![避免將語句與演算法放在同一行](https://rvso.com/image/254725/%E9%81%BF%E5%85%8D%E5%B0%87%E8%AA%9E%E5%8F%A5%E8%88%87%E6%BC%94%E7%AE%97%E6%B3%95%E6%94%BE%E5%9C%A8%E5%90%8C%E4%B8%80%E8%A1%8C.png)
我正在編寫一個簡單的偽代碼,但我遇到了重複..直到塊的問題。基本上發生的情況是,這個循環結束後的 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}}