[英]C# (find second largest number) How to split program in subprograms ?so I can reuse code later…?
I have this program that finds second largest number from users input, user needs to input atleast 2 numbers and maximum 10. I want to split program into subprograms(at least main and one function). 我有这个程序,它从用户输入中查找第二大数字,用户需要输入至少2个数字和最大10个数字。我想将程序分为子程序(至少主程序和一个函数)。 And i cant get it to work :(
我不能让它工作:(
Org. 单位 code:
码:
static void Main(string[] args)
{
int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0;
while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
n = int.Parse(Console.ReadLine());
//I want this part to be in a function from here.
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
//to here
if (n == smax)
{
ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1 it outputs error
}
i++;
}
if (smax != 0 && smax != ISsmaxrepeating)
{
Console.WriteLine("secondmax is {0}", smax);
}
else
{
Console.WriteLine("error");
}
Console.ReadLine();
So far I come up with this but it is not working :( 到目前为止,我想出了这个,但它没有用:(
static int checking(int n, int max, int smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
return n;
}
static void Main(string[] args)
{
int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0, result = 0;
while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
n = int.Parse(Console.ReadLine());
result = checking(n,max,smax);
if (n == smax)
{
ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1 it outputs error
}
i++;
}
if (smax != 0 && smax != ISsmaxrepeating)
{
Console.WriteLine("secondmax is {0}", smax);
}
else
{
Console.WriteLine("error");
}
Console.ReadLine();
}
You can output multiple variables from the function using ref
keyword. 您可以使用
ref
关键字从函数输出多个变量。 However, it's better not to use a function for this kind of operation. 但是,最好不要对此类操作使用函数。
static void checking(int n, ref int max, ref int smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
}
Call the function inside Main
调用
Main
内部的函数
checking(n, ref max, ref smax);
Why dont.you use Math.max or Math.min? 为什么不使用Math.max或Math.min? If.you want to find highest between 3 numbes, first do int halfmax=math.max(firstnum,secondnum) then do int max = Math.max(halfmaz,thirdnum).
如果要查找3个数字之间的最大值,请先执行int halfmax = math.max(firstnum,secondnum),然后再执行int max = Math.max(halfmaz,thirdnum)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.