繁体   English   中英

从数组中的2个数字中查找最大和最小数量

[英]finding maximum & minimum number from 2 numbers in an array

我试图找出用户输入的2个整数中的最大和最小数字。 首先,我已将字符串转换为int,然后将它们放入数组中,以便我可以操作它们。 我认为在将变量分配给数组时我会陷入困境。 但我看不到任何分配了变量的数组的例子,这可能就是我出错的地方。

    private void button1_Click(object sender, EventArgs e)
    {
       string txtbxnum1 = Int32.Parse(num1);
       string txtbxnum2 = Int32.Parse(num2);

       int[] numbers = new int[2] {0,1};
       int numbers [0] = num1;
       int numbers [1] = num2;

       int maximumNumber = Max.numbers();
       int minimumNumber = Min.numbers();
       MessageBox.Show (maximumNumber.Text);
    }

我很乐意得到任何帮助或指导。

如果只有两个数字,则不需要数组: System.Math提供了查找两个数字中较小和较大的函数,称为Math.MaxMath.Min

// Int32.Parse takes a string, and returns an int, not a string:
int n1 = Int32.Parse(num1);
int n2 = Int32.Parse(num2);
// Math.Min and Math.Max functions pick the min and max
int min = Math.Min(n1, n2);
int max = Math.Max(n1, n2);
// Show both numbers in a message box in one go using String.Format:
MessageBox.Show(string.Format("Min:{0} Max:{1}", min, max));

有点搞砸了语法。 您的代码不是 C#语言的有效代码。

你必须做这样的事情:

var numbers = new int[]{0,1,567,4,-5,0,67....};

和max / min很简单

var maximum = numbers.Max();
var minimum = numbers.Min();

您应该调用Math.MinMath.Max ,它们都接受两个整数作为参数。

如果这还不够详细,请告诉我。

int maximumNumber = Math.Max(numbers[0],numbers[1]);
int minimumNumber = Math.Min(numbers[0],numbers[1]);

MessageBox.Show(maximumNumber + " " is the largest and " + minimumNumber + " is the smallest");

那说你不应该真正访问这样的数组值,但它适用于初学者。

我不太了解你与TextBoxes的交互和奇怪的解析然后设置为字符串,但假设num1和num2是用户输入的整数

private void button1_Click(object sender, EventArgs e)
{
    int maximumNumber = Math.Max(num1, num2);
    int minimumNumber = Math.Min(num1, num2);

    MessageBox.Show (maximumNumber);
}

您的代码中存在一些错误。

string txtbxnum1 = Int32.Parse(num1);

Int32.Parse接受一个字符串并返回一个int 但是,您正在尝试将其分配给string 它应该是

int txtbxnum1 = Int32.Parse(num1);

像这样分配一个数组:

int[] numbers = new int[2] {0,1};

只需创建一个新数组,该数组可以包含两个整数,并使用值01预填充它们。 这不是你想要做的。 据我所知,你甚至不需要在这里使用数组,除非你在代码中的其他地方使用它。

您可以使用Math类中的方法找到MaxMin值。

int minimumValue = Math.Min(txtbxnum1,txtbxnum2);
int maximumValue = Math.Max(txtbxnum1,txtbxnum2);

您可以在MSDN上找到有关Math类的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM