A challenge!
Here is the shortest calculator possible in C code that implements the operators +, -, *, /:
#include <stdio.h>
int main() {
float a, b; char o;
scanf("%f %c %f", &a, &o, &b);
printf("%f\n", o==43?a+b:o==45?a-b:o==42?a*b:o==47?a/b:0);
return 0;
}
Let's break it down:
- We use
float to support decimal numbers.
- We read 3 inputs: two
floats (a and b) and a char (o) representing the operator, using scanf. The format string "%f %c %f" expects input like 2 + 3.
- The magic happens in the
printf statement. We use a single, nested ternary expression to evaluate the operation based on the ASCII value of the operator character o:
43 is the ASCII code for +
45 is the ASCII code for -
42 is the ASCII code for *
47 is the ASCII code for /
- If
o doesn't match any of these, we default to 0 (which will be printed as the result).
Here's how it works:
o==43?a+b:o==45?a-b:... is like a nested if-else:
- If
o is + (43), return a+b.
- Else, if
o is - (45), return a-b.
- Else, ... (and so on for
* and /)
- The final
0 is returned if o doesn't match any operator (e.g., if user inputs 2 x 3).
Example usage:
$ ./calc
2 + 3
5.000000
$ ./calc
4 * 5
20.000000
$ ./calc
7 / 2
3.500000
$ ./calc
1 - 6
-5.000000
Notes:
- No error handling for division by zero (e.g.,
2 / 0 will produce inf or crash).
- No validation for invalid operator inputs (e.g.,
2 x 3 will print 0).
- The output format is fixed (
%f\n), always showing 6 decimal places.
If you want a tiny bit more robustness (division by zero check), here's a 2-line longer version:
#include <stdio.h>
int main() {
float a, b; char o;
scanf("%f %c %f", &a, &o, &b);
printf("%f\n", o==43?a+b:o==45?a-b:o==42?a*b:(b?o==47?a/b:0/0:0/0));
return 0;
}
Here, (b?o==47?a/b:0/0:0/0) checks if b is non-zero before performing division. If b is zero, 0/0 will produce a NaN (Not a Number) output.
That's still extremely concise!
Compile with gcc calc.c -o calc (assuming you save the code in calc.c). Enjoy your ultra-compact calculator!