
我希望你幫我使用 TeXstudio 使用 for 迴圈來寫一個演算法。對於高斯消去法我有程式碼:
for (int i = 0; i < N-1; i++) {
for (int j = i; j < N; j++) {
double ratio = A[j][i]/A[i][i];
for (int k = i; k < N; k++) {
A[j][k] -= (ratio*A[i][k]);
b[j] -= (ratio*b[i]);
}
}
}
答案1
編寫程式碼的一種方法是使用該listings
套件。然後你的高斯消除演算法將被寫成:
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstset{ %
backgroundcolor = \color{white}, % Background color
keywordstyle = \color{blue}, % Keyword style (just color here)
numbers = left, % Add line number to the left of the code
captionpos = b % Caption at the bottom of the listing
}
\begin{document}
\begin{lstlisting}[language = C, caption={Gaussian elimination algorithm}]
for (int i = 0; i < N-1; i++) {
for (int j = i; j < N; j++) {
double ratio = A[j][i]/A[i][i];
for (int k = i; k < N; k++) {
A[j][k] -= (ratio*A[i][k]);
b[j] -= (ratio*b[i]);
}
}
}
\end{lstlisting}
\end{document}
如果您不想為程式碼新增任何標題,只需刪除環境caption
開頭的選項即可lstlisting
。如果語言不是 C,您可以隨時將選項變更language
為您正在使用的語言。
答案2
對應的偽代碼;這裡使用了algorithm
和包。algpseudocode
\documentclass{article}
\usepackage{algorithm} % Required for pseudo code
\usepackage[noend]{algpseudocode} % Required for pseudo code
\renewcommand{\algorithmicrequire}{\textbf{Input:}} % Changes 'Require' to 'Input'
\begin{document}
\begin{algorithm}
\caption{Caption of pseudo code}
\begin{algorithmic}
\Require $A$
\For{$i \gets 0$ to $N - 2 $}
\For{$j \gets i$ to $N - 1 $}
\State $ratio \gets A[j][i]/A[i][i]$
\For{$k \gets i$ to $N - 1 $}
\State $A[j][k] \gets A[j][k] - (ratio*A[i][k])$
\State $b[j] \gets b[j] - (ratio*b[i])$
\EndFor
\EndFor
\EndFor
\end{algorithmic}
\label{alg:code_label}
\end{algorithm}
\end{document}