在一行中写入“If Then Else”

在一行中写入“If Then Else”

一行中可以有“if..then..else”吗?

我正在寻找方法来压缩占用我文章大量空间的简单条件语句。因此,任何帮助我都感激不尽。

\documentclass[conference]{IEEEtran}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage[noend]{algpseudocode}

\begin{document}
    \title{HOWTO Single Line If Then Else}
    \author{Author}
    \maketitle

\begin{abstract}
    This is an abstract.
\end{abstract}

\hspace{10pt}

\begin{IEEEkeywords}
    a, b, c, d.
\end{IEEEkeywords}
\IEEEpeerreviewmaketitle

\section{Introduction}

\begin{algorithm}
    \caption{Single line IF THEN ELSE}\label{alg:IfThenElse}
    {\fontsize{8}{8}\selectfont
        \begin{algorithmic}[1]
            \If {$\text{foo} \leq \text{bar}$} $doh$ = 0
            \Else {} $\text{duh}$ = 1
            \EndIf
        \end{algorithmic}
    }
\end{algorithm}
\end{document}

答案1

实现此目的的一个相当基本(但有效)的方法是使用\IfThenElse{<if>}{<then>}{<else>}

\algnewcommand{\IfThenElse}[3]{% \IfThenElse{<if>}{<then>}{<else>}
  \State \algorithmicif\ #1\ \algorithmicthen\ #2\ \algorithmicelse\ #3}

它只是将所有需要的组件设置\State在一起。

在此处输入图片描述

\documentclass[conference]{IEEEtran}

\usepackage{amsmath}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}

\algnewcommand{\IfThenElse}[3]{% \IfThenElse{<if>}{<then>}{<else>}
  \State \algorithmicif\ #1\ \algorithmicthen\ #2\ \algorithmicelse\ #3}

\begin{document}

\title{HOWTO Single Line If Then Else}
\author{Author}
\maketitle

\begin{abstract}
This is an abstract.
\end{abstract}

\begin{IEEEkeywords}
a, b, c, d.
\end{IEEEkeywords}
\IEEEpeerreviewmaketitle

\section{Introduction}

\begin{algorithm}
  \caption{Single line IF THEN ELSE}
  \begin{algorithmic}[1]
    \If {$\text{foo} \leq \text{bar}$} $\text{doh} = 0$
    \Else {} $\text{duh} = 1$
    \EndIf
    \IfThenElse {$\text{foo} \leq \text{bar}$}% If ...
      {$\text{doh} = 0$}% ...then...
      {$\text{duh} = 1$}% ...else...
  \end{algorithmic}
\end{algorithm}

\end{document}

相关内容