0

Trying to have method store variables to compare until it needs to be printed

Student new to C#. I am trying to create a simple method that when called and has input placed in the parameters, it will compare the numbers. After all methods rans and numbers entered, it should output which of those numbers is the greatest. My thoughts where that I could somehow update an optional parameter to hold the value until the end but I keep hitting dead ends where the last number I input is "the greatest". I think my mistake is the "returnedNum" variable but I'm lost on how to somehow have the program update and store the new "biggest number" as whatever the previous one was until it needs to be printed. Am I on the right track with the thought process or what better way is there to have it do this without a ton of if statements? Code listed below using System; class Program { public static void Main (string[] args) { //collects all user input as ints right away Console.WriteLine("Enter the first Number: "); int getNum1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the second Number: "); int getNum2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the third Number: "); int getNum3 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the fourth Number: "); int getNum4 = Convert.ToInt32(Console.ReadLine()); LargestNum(getNum1, getNum2); LargestNum(getNum3); int returnedNum = LargestNum(getNum4); Console.Write("The Largest Number is: " + returnedNum); } public static int LargestNum( int num1, int num2 = 0) { if (num1 > num2) { num2 = num1; return num2; } else { return num2; } } }

11th Feb 2022, 11:39 PM
John D4
1 Odpowiedź
+ 1
getNum4 is going to be always printed as the largest, because it is the only one that is assigned to returnedNum the other ones you just called the function without storing its returned value. I think a better approach is to use an array to store input values then sort the array, or just use built in methods to get the largest number. https://code.sololearn.com/cK71A1PjoB8j/?ref=app
12th Feb 2022, 12:15 AM
Bahhaⵣ
Bahhaⵣ - avatar