我有这个程序从用户输入中找到第二大数字,用户需要输入至少2个数字和最多10个。我想将程序分成子程序(至少主要和一个功能)。我无法让它工作:(
单位。代码:
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();
到目前为止,我想出了这个,但它无法正常工作:(
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();
}
答案 0 :(得分:1)
您可以使用ref
关键字从函数中输出多个变量。但是,最好不要使用函数进行此类操作。
static void checking(int n, ref int max, ref int smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
}
在Main
checking(n, ref max, ref smax);
答案 1 :(得分:0)
为什么不使用Math.max或Math.min? If.you想要找到3个numbes之间的最高值,首先要做int halfmax = math.max(firstnum,secondnum) 然后做int max = Math.max(halfmaz,thirdnum)。