5

我试图从用户输入的 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);
    }

我会很高兴得到任何帮助或指导。

4

6 回答 6

6

如果您只有两个数字,则不需要数组: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));
于 2012-10-24T21:34:56.500 回答
2

您应该调用Math.Min并且Math.Max两者都接受两个整数作为参数。

让我知道这是否不够详细。

于 2012-10-24T21:34:44.467 回答
2

语法有点混乱。您的代码不是 C#语言有效的代码。

你必须做这样的事情:

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

而 max/min 就像

var maximum = numbers.Max();
var minimum = numbers.Min();
于 2012-10-24T21:34:39.433 回答
0
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");

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

于 2012-10-24T21:34:48.810 回答
0

我不太了解您与 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);
}
于 2012-10-24T21:36:17.403 回答
0

您的代码中有一些错误。

string txtbxnum1 = Int32.Parse(num1);

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

int txtbxnum1 = Int32.Parse(num1);

像这样分配一个数组:

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

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

您可以使用类中的方法找到Max和值。MinMath

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

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

于 2012-10-24T21:37:54.043 回答