我正在尝试从用户输入的 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.Max
和 Math.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/