Is it possible to do this with only 2 variables?
Thanks
Is it possible to do this with only 2 variables?
Thanks
Why don't you try to do it with only two variables, and see if you can?
I've come to the conclusion that it's not possible as you are comparing three numbers.
Perhaps the challenge was 2 comparisons (which is possible), not 2 variables (which isn't).
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Apparently you can use arrays.
Or, if you count the three input values in an array as one variable, the trivial solution uses exactly two variables and two comparisons.
Edit: Since qny posted one below, I'll post this one too.
and for any number of values using just three variables and (numbers - 1) comparisons (of numbers; (2*numbers - 1) if you count the loop condition comparison too):Code:double maximum_of_three(const double *numbers) { double max = *numbers; if (*(++numbers) > max) max = *numbers; if (*(++numbers) > max) max = *numbers; return max; }
Code:double maximum(const double *numbers, size_t count) { double max = *numbers; while (count-- > 1) if (*(++numbers) > max) max = *numbers; return max; }
Last edited by Nominal Animal; 10-10-2012 at 08:57 AM.