# ifelse 函数

由测试条件选出的值。

## 怎么写

### ifelse(test, then, else)

测试为真时的第一个值，为假时的第二个值。

**test**

一个真或假的条件，例如 x > 0。接受一个条件，真或假。

**then**

测试为真时的结果。接受一个表达式。

**else**

测试为假时的结果。接受一个表达式。

### ifelse(test, then, else, unknown)

为无法判定的测试给出结果。

**test**

一个真或假的条件，例如 x > 0。接受一个条件，真或假。

**then**

测试为真时的结果。接受一个表达式。

**else**

测试为假时的结果。接受一个表达式。

**unknown**

测试无法判定时的结果，例如符号 x 的 x > 0。接受一个表达式。

## 示例

- $\displaystyle \operatorname{ifelse}(1 < 2, 10, 20) = 10$

  `ifelse(1 < 2, 10, 20)`

  在求解器中，`ifelse(1 < 2, 10, 20)` 的结果是 `10`。

  [在求解器中打开](https://zh.hilberon.com/?q=ifelse%281%20%3C%202%2C%2010%2C%2020%29)
- $\displaystyle \operatorname{ifelse}(x > 0, 1, 2, 3) = 3$

  `ifelse(x > 0, 1, 2, 3)`

  在求解器中，`ifelse(x > 0, 1, 2, 3)` 的结果是 `3`。

  [在求解器中打开](https://zh.hilberon.com/?q=ifelse%28x%20%3E%200%2C%201%2C%202%2C%203%29)

## 相关函数

- [increment](https://zh.hilberon.com/library/increment)

  将变量原地加 1，并返回它的旧值。
- [function](https://zh.hilberon.com/library/function)

  没有名字的函数；也可写作 x => body。
- [indicator](https://zh.hilberon.com/library/indicator)

  把条件表示为数：为真时为 1，为假时为 0。
- [evaluate](https://zh.hilberon.com/library/evaluate)

  对表达式求值，即使它本应保持不计算。
- [piecewise](https://zh.hilberon.com/library/piecewise)

  按条件写出的分段取值，写作 value if condition，并可带一个 otherwise 分支。
- [divide_by](https://zh.hilberon.com/library/divide_by)

  将变量就地除以一个值，并返回新的值。

---
Source: https://zh.hilberon.com/library/ifelse
