Here's one: Explain what this does. The prompts are taken out so that this isn't too obvious. BTW, this is C++, not PHP just in case you didn't pick up on that.
#include<iostream>
int calc(int a, int b, char op) {
return op == '+' ? a + b : ( op == '-' ? a - b : ( op == '*' ? a * b :op == '/' ? a / b : a % b ));
}
int main () {
int a, b;
char op;
cin >> a >> op >> b;
cout << calc(a, b, op) << endl;
}
If you want to compile this for some awful reason, and for another awful reason you're using VC++, throw using namespace std; in there before the I/O. I use GNU g++ 2.95.3 on AIX 4.3.3, so I get away without all of the requirements of the standard.
It's actually kinda useful, I do really use this on a regular basis. And yes, I know this could have been all done in main, but that takes the fun of a one line function away. Just something I did a few months ago to demonstrate ?: and it's ability to be nested, though much more gets a little unreadable.
BPM |