Finding maximum of 3 numbers using nested if/else statements

北战南征 提交于 2019-12-10 11:29:09

问题


So I'm in college and I'm writing a program using C# which is ALMOST done except for this button. I don't want the answer because I'll never learn that way, but I'm writing a program using Heron's method where the user has to input 3 numbers to determine if these numbers can be used as sides of a triangle. The one button I am confused with is the Finding the Maximum button which wants the program to show which number entered is the highest. The professor wants this code to be written using nested if/else statements. I have searched online and the book for the course is terrible. Could someone help me with a possible web site to help or maybe an example? That would be GREATLY appreciated.


回答1:


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.




回答2:


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 */
}



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/12572044/finding-maximum-of-3-numbers-using-nested-if-else-statements

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