Finding maximum of 3 numbers using nested if/else statements

谁都会走 提交于 2019-12-06 13:39:12

Perhaps you could write it using a two-level nested Math.Max(v1, v2) request. Then translate that into the necessary If/else clauses. Maybe you can get bonus points if you download ILSpy and inspect System.Math.Max to see what .Net uses under the covers.

I remember problems like these from university. Break the solution down so that you're comparing two of the numbers at a time. Once you have the maximum from the first pair, compare that to the third. Something like:

int a, b, c;

if (a > b)
{
    if (a > c)
        return a;
    else
        return c;
}
else
{
    /* similar for b/c pair */
}

If you need I can write the entire program. But to get max outta three numbers here is the pseudo code.

`var n1 = GetInputFromUser` >> General methods in C# console is Console.Readline() and in case of forms its good ole TextBoxes.
var n2 = GetInputFromUser
var n3 = GetInputFromUser

var result

if (n1 > n2)
        {
            result = n1;

            if (n1 > n3)
                result = n1;
            else
                result = n3;
        }
        else
        {
            result = n2;
            if(n2 > n3)
                result = n2;
            else
                result = n3;
        }

Hope this helps

If you have to use nested if statements, I would look into using a temp variable. something like:

var temp
var input1
var input2
var input3

if input1> input2 then
     temp = input1
else
    temp = input2

Something similar to this should be sufficient. I didn't go into the whole thing as only an example was asked for, and OP specifically said they didn't want the answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!