我需要您的帮助,使用 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}