How can I convert an if..else if..else statement to a single formula

667 Views Asked by At

I have this program where I made a variable x, and I want to assign it a value based on this formula (where c is a positive integer): $$ x = f(c) = \begin{cases} c & c<100\\100 & 100<=c<200\\c-100 & c>=200 \end{cases} $$ At the moment I have this in some code using an if statement, but I'd like to have this using a single assignment with just a formula and no if statements.

  int x;
  if (c < 100) 
    x = c;
  else if (c < 200)
    x = 100;
  else
    x = c-100;

I've heard that if statements like this can be converted into some formula, but I'm not sure where to start, any help would be appreciated! In the end, I'll hopefully have just one statement:

int x = f(c);
4

There are 4 best solutions below

6
On BEST ANSWER

You could use: $$f(c) = c-50+\frac{|c-200|-|c-100|}{2}$$

Wolfram Alpha

4
On

In computability theory I've found the following notation

$f(x) = x\cdot \chi_{x<100} + 100 \cdot \chi_{100\leq x<200} + (x-100)\cdot \chi_{x\geq 200}$

where $\chi_A$ ($A$ is a set) is a 0-1 function such that $\chi_A (x) = 1$ if $x\in A$ and $0$ otherise.

1
On

Most programming languages have some ternary-if function. In can look like (c, c++, java)

int x = c < 100 ? c : c < 200 ? 100 : c - 100;

or (python)

x = c if c < 100 else 100 if c < 200 else c - 100

This cleanly expresses the intent of your assignment. Parenthesis are not needed in this case, but you may want to add them to make it even clearer, e.g.,

int x = c < 100 ? c : (c < 200 ? 100 : c - 100);

Now, these don't contain if statements, but they do contain if expressions. If you're not happy with that, you need to resort to trickery as in Jaap Scherphuis' answer.

0
On

Define a function like this

int f(int c){
  if (c < 100) 
    return c;
  else if (c < 200)
    return 100;
  else
    return c-100
}

Now you can call it in one statement like this, as required.

int x = f(c);