c# - 从数组中的2个数字中找到最大和最小数

标签 c#

我正在尝试从用户输入的 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# - 从数组中的2个数字中找到最大和最小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13058103/

相关文章:

c# - 使用 RSA AES 提供程序生成自签名 1024 位 X509Certificate2 时出现问题

c# - 将 Kinect 深度读数映射到 Unity

c# - 使用扩展方法复制数组

c# - 如果捕获一般异常,是否有可能出现异常?

c# - XML ws 服务中的 Web 服务土耳其语字符

c# - 在 ASP.NET WebForm 中输入按键事件执行按钮点击

c# - 找不到 Microsoft.Office.Interop Visual Studio

C# Mutex Timespan 向新手解释

c# - 保存和解析枚举集合的最快方法?

C# 处理所有可能的空值和非空值