settingsAccountsettings
Menusettings

Q: Get two numbers and print the greater of them (without if statements)

+7 votes

I need to write a program which gets two numbers from the console and prints the greater of them.

However - I must do it without implementing the if statements.

Examples:

a

b

greater

5

6

6

10

5

10

0

0

0

-5

-2

-2

1.5

1.6

1.6

 

asked in C# category by user ak47seo

1 Answer

+2 votes
 
Best answer

You can use the Math.Max Method (Double, Double) for this purpose.

It returns the larger of two double-precision floating-point numbers: https://msdn.microsoft.com/en-us/library/7x97k0y4%28v=vs.110%29.aspx

So the code will look like this:

using System;

class NumberComparer
{
    static void Main()
    {
        Console.WriteLine("Please write the first number to compare: ");
        double firstNumber = double.Parse(Console.ReadLine());

        Console.WriteLine("Please write the second number to compare: ");
        double secondNumber = double.Parse(Console.ReadLine());

        double compareNumbers = Math.Max(firstNumber, secondNumber);
        Console.WriteLine("Number {0} is greater",compareNumbers);
    }
}

 

compare two numbers in c sharp - Visual Basics with Math.Max method

answered by user richard8502
edited by user golearnweb
...