计算误差宽度

计算误差宽度

我尝试在 \ifdimcomp 命令(etoolbox 包)中使用 \widthof 命令(calc 包),但一直收到错误“缺少数字,视为零”,这让我很困惑。我尝试测试一行文本是否可以放在一行中。如果我用指定的单位长度替换 \widthof 命令,\ifdimcomp 命令可以工作,但不是我想要的那样。

\documentclass{article}
\usepackage{calc}
\usepackage{etoolbox}
\newcommand{\cmd}[1]{%
    %\ifdimcomp{〈dimen expression〉}{〈relation〉}{〈dimen expression〉}{〈true〉}{〈false〉}; see etoolbox package
    \ifdimcomp{\widthof{#1}}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\cmdtwo}[1]{%
    %\ifdimcomp{〈dimen expression〉}{〈relation〉}{〈dimen expression〉}{〈true〉}{〈false〉}; see etoolbox package
    \ifdimcomp{11pt}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\alphabet}{abcdefghijklmnopqrstuvwxyz}
\begin{document}
\cmd{Hello world}\par%doesnt work
\cmd{\alphabet}\par%doesnt work
\cmd{\alphabet\alphabet\alphabet\alphabet}\par%doesnt work
\cmdtwo{Welcome to the wonderful world of learning latex on the latex stack exchange forums!}\par%works
\cmdtwo{\alphabet\alphabet\alphabet\alphabet}%works
\end{document}

答案1

如果你尝试最简单的例子,你就能明白为什么会发生这种情况

\documentclass{article}
\usepackage{calc}

\begin{document}

\widthof{test}

\end{document}

输出结果不是test宽度数字,实际上\widthof并不可靠,因为只在特定场景下有效。

我建议换个方式

\documentclass{article}
\usepackage{calc}
\usepackage{etoolbox}
\newcommand{\cmd}[1]{%
    \sbox0{#1}
    \ifdimcomp{\wd0}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\cmdtwo}[1]{%
    \ifdimcomp{11pt}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\alphabet}{abcdefghijklmnopqrstuvwxyz}
\begin{document}
\cmd{Hello world}\par%works
\cmd{\alphabet}\par%works
\cmd{\alphabet\alphabet\alphabet\alphabet}\par%work
\cmdtwo{Welcome to the wonderful world of learning latex on the latex stack exchange forums!}\par%works
\cmdtwo{\alphabet\alphabet\alphabet\alphabet}%works
\end{document}

相关内容