x = (x>=y) ? x : y;
Comment: This question would be trivial for people familiar with C or C++. The in-line condition statement is used extensively by experienced programmers and is something every C/C++ programmer should know.
BTW, when you’re asked to write sample programming code, don’t forget any end-of-statement semicolons or other elements that make a statement in the chosen language valid. On the other hand, you need not initialize or even declare variables if they’re clearl from the context, as in this sample question.
for this case
z = std::max(x, y);
clearly defines the intent, without resorting to the tenary operator. ?: has it’s uses but the min/max pattern should not be one of them.
x = ( x + y + abs( x – y ) ) / 2
That doesn’t work if the intermediate overflows. Your algorithm produces -1 for:
int x = INT_MAX;int y = INT_MAX – 1;
I’m not that familiar with C++. I guess this would do for both C++ and Matlabx = (x>=y)*x + (x<y)*y;
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
You are commenting using your Google+ account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.