-5

The greatest of two numbers without any conditional statements. I need to get two numbers from the user and find out the greatest of them but I can't figure it out.

Milo
  • 3,365
  • 9
  • 30
  • 44
  • 4
    You can use [`Math.Max`](https://learn.microsoft.com/en-us/dotnet/api/system.math.max?view=netframework-4.8) – Tim Schmelter Dec 21 '19 at 01:14
  • Does this answer your question? [What's the best way to compare Double and Int?](https://stackoverflow.com/questions/1650091/whats-the-best-way-to-compare-double-and-int) – bad_coder Dec 21 '19 at 03:58

2 Answers2

1

There are many ways to solve this but I would solve this by sorting numbers in a descending way. Try this:

int[] numbers = { 10, 20};
Array.Sort(numbers);
Array.Reverse(numbers);
Console.WriteLine("The highest number is: " + numbers[0]);

Or, just use numbers.Max() instead of Array.Sort(numbers) and Array.Reverse(numbers). There are still more than 20 ways to solve this problem.

EthernalHusky
  • 485
  • 7
  • 19
  • This does not sort the array, it just reverses the order. – Ron Beyer Dec 21 '19 at 02:01
  • I forgot to add `Array.Sort(numbers);`. Now it works. – EthernalHusky Dec 21 '19 at 02:09
  • I didn't down vote, but your array is only two numbers and you are sorting it, why do you need to reverse it? You know that the last element will contain the largest number... – Ron Beyer Dec 21 '19 at 02:12
  • `Array.Sort(numbers)` sorts in a ascending way like 1, 45, 67, 22, 88, ..., and reverse them to get the highest number in the first position of the array. This code is useful if he is using more than two numbers. – Reyneer Leon Dec 21 '19 at 02:18
  • I tested the code with `int[] numbers = {12, 45, 34, 99, 3, 95, 34, 1, 2, 3, 5};` and got 99. It works. But if he is using two numbers, code still works. – EthernalHusky Dec 21 '19 at 02:22
0

You can use Math.Max, but it is a wrapper around a ternary statement that looks like this:

return (val1>=val2)?val1:val2;

There is a different way...

var array = new double[] { userValue1, userValue2 };
var largest = array.Max();

Or you can sort the array in descending order and get the first element... Really though all programming boils down to a conditional somewhere, and .Max() is no different, it just sorts the array and gets the biggest value.

Ron Beyer
  • 11,003
  • 1
  • 19
  • 37