在方程式中使用新命令時插入的字元遺失

在方程式中使用新命令時插入的字元遺失

我遇到了一個似乎無法解決的問題。我想定義一個數學符號,並在程式碼片段中顯示,我在整個文字中經常使用它。當我想在方程式中包含相同的符號時,我收到很多“插入缺失字元”錯誤,並且另一側的格式錯誤。

\documentclass[12pt]{article}
\usepackage{amsmath,amssymb}

\newcommand{\WPT}{$p_{\text{T}}^W$}

\begin{document}
The result for \WPT is shown below.

\begin{equation}
  r_s^{\WPT} &= 100.00
\end{equation}

\end{document}

在此先感謝您的幫忙。

答案1

如果我運行您發布的程式碼,我會收到錯誤:

! Missing } inserted.
<inserted text> 
                }
l.10   r_s^{\WPT
                } = 100.00
?

發生此錯誤是因為當您的命令擴展時(直到錯誤發生的地方)基本上:

$$ r_s^{ $

這不是一個有效的 TeX 結構。您開始顯示數學,開始一個群組,然後結束內聯數學。後來 TeX 會說:

! Display math should end with $$.
<to be read again> 
                   p
l.13   r_s^{$p
              _{\text{T}}^W$} = 100
?

試圖解決所有這些問題時會變得更加困惑。


您可以使用\ensuremath它,正如其名稱所示,確保其內容以數學模式排版(請注意此處文本中的額外內容){}\WPT

\documentclass[12pt]{article}
\usepackage{amsmath,amssymb}

\newcommand{\WPT}{\ensuremath{p_{\text{T}}^W}}

\begin{document}
The result for \WPT{} is shown below.

\begin{equation}
  r_s^{\WPT} = 100.00
\end{equation}

\end{document}

但是,由於\WPT本質上是數學內容,我會選擇適當的標記並在文本中\WPT包含$... :$

\documentclass[12pt]{article}
\usepackage{amsmath,amssymb}

\newcommand{\WPT}{p_{\text{T}}^W}

\begin{document}
The result for $\WPT$ is shown below.

\begin{equation}
  r_s^{\WPT} = 100.00
\end{equation}

\end{document}

相關內容