如何使用 \newcommand 块中的可选参数进行计算?
How can I calculate with optional parameter in \newcommand block?
我想要一个可以调整到所需高度的网格命令。这是我所做的:
\newcommand{\vhlines}[1]{
\hspace{1em}
\setlength{\unitlength}{0.75cm}
\begin{picture}(22,#1)
\color{lightgray}
\linethickness{0.075mm}
\multiput(0,0)(1,0){21}
{\line(0,1){#1}} % need to subtract 1 from #1
\multiput(0,0)(0,1){#1}
{\line(1,0){20}}
\end{picture}
}
如果我调用,例如,\vhlines{16}
,我发现垂直线在上端太长。如果我在注释行中写 15
而不是 #1
,它们是正确的。
有没有优雅的方法来做到这一点?
您可以使用 \numexpr
:
执行基本数值(整数)表达式
\documentclass{article}
\usepackage{xcolor}
\newcommand{\vhlines}[1]{%
\hspace{1em}%
\setlength{\unitlength}{0.75cm}%
\begin{picture}(22,#1)
\color{lightgray}
\linethickness{0.075mm}
\multiput(0,0)(1,0){21}
{\line(0,1){\numexpr#1-1}}
\multiput(0,0)(0,1){#1}
{\line(1,0){20}}
\end{picture}
}
\begin{document}
\noindent
\vhlines{4}
\end{document}
或者,对于更复杂的表达式,添加到您的序言中
\usepackage{xparse}
\ExplSyntaxOn
\cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff
这将允许您使用 \calc{<your numerical expression>}
。
我想要一个可以调整到所需高度的网格命令。这是我所做的:
\newcommand{\vhlines}[1]{
\hspace{1em}
\setlength{\unitlength}{0.75cm}
\begin{picture}(22,#1)
\color{lightgray}
\linethickness{0.075mm}
\multiput(0,0)(1,0){21}
{\line(0,1){#1}} % need to subtract 1 from #1
\multiput(0,0)(0,1){#1}
{\line(1,0){20}}
\end{picture}
}
如果我调用,例如,\vhlines{16}
,我发现垂直线在上端太长。如果我在注释行中写 15
而不是 #1
,它们是正确的。
有没有优雅的方法来做到这一点?
您可以使用 \numexpr
:
\documentclass{article}
\usepackage{xcolor}
\newcommand{\vhlines}[1]{%
\hspace{1em}%
\setlength{\unitlength}{0.75cm}%
\begin{picture}(22,#1)
\color{lightgray}
\linethickness{0.075mm}
\multiput(0,0)(1,0){21}
{\line(0,1){\numexpr#1-1}}
\multiput(0,0)(0,1){#1}
{\line(1,0){20}}
\end{picture}
}
\begin{document}
\noindent
\vhlines{4}
\end{document}
或者,对于更复杂的表达式,添加到您的序言中
\usepackage{xparse}
\ExplSyntaxOn
\cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff
这将允许您使用 \calc{<your numerical expression>}
。