我见过许多与同一类问题相关的类似问题和答案,但它们要么没有得到很好的解释,要么在某个地方的翻译中丢失了某些内容。
所以我想制作这个超级简单的 MWE,一劳永逸地解决它,为我自己以及所有当前和未来的 LaTeX 新手。这样,当出现更复杂的用例时,应该很容易调整该技术,而不是尝试对简单用途的复杂示例进行逆向工程。
我希望这是有意义的,无论如何它在这里:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{amsmath}
\usepackage{pgffor}
\usepackage{tikz}
\usepackage{calc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usetikzlibrary{calc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\foreach \x in {1,...,5} { $(\x-1)$ }
\end{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
循环运行正常,但计算不正常。
所需的输出只是类似于以下内容:
01234
但我得到的却是一些更为直接的答案,例如:
(1-1)(2-2)(3-3)(4-4)(5-5)
答案1
这里有两种替代方法evaluate
。您可以使用\the\numexpr
或直接循环0,...,4
。只pgffor
需要 即可。
\documentclass{article}
\usepackage{amsmath}
\usepackage{pgffor}
\begin{document}
\foreach \x in {1,...,5} { $(\the\numexpr\x-1)$ }
\foreach \x in {0,...,4} { $(\x)$ }
\end{document}
答案2
[evaluate=\x as... using...]
Tikz 允许使用参见 3.1.3 手册第 983 和 984 页的语法对变量执行计算。
\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{amsmath}
\usepackage{pgffor}
\usepackage{tikz}
\usepackage{calc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usetikzlibrary{calc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\foreach \x [evaluate=\x as \xx using int(\x-1)]in {1,...,5} { $\xx$ }
\end{document}
答案3
概念证明expl3
:
\documentclass{article}
\usepackage{xparse,xfp}
\ExplSyntaxOn
\NewDocumentCommand{\intloop}{O{1}mm}
{% #1 = start, default 1; #2 = end; #3 = template
\cs_gset_protected:Nn \__tjt_intloop_function:n { #3 }
\tjt_intloop:nn { #1 } { #2 }
}
\cs_new:Nn \tjt_intloop:nn
{
\int_step_function:nnN { #1 } { #2 } \__tjt_intloop_function:n
}
\ExplSyntaxOff
\begin{document}
\intloop{5}{\inteval{#1-1}}
\bigskip
$\begin{array}{c|c}
n & f(n) \\
\hline
\intloop{5}{#1 & \fpeval{2*(#1)^2-4} \\}
\end{array}$
\end{document}