using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var numbers = textBox1.Text.Split(' ');
var min = numbers.Min();
var max = numbers.Max();
textBox2.Text = string.Format("min: {0} max: {1}", min, max);
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
当用户键入 (1 2 3 4 5 6 7 8 9 10) 时无法显示正确的最大值 我是编程新手,我对将 max {0} 更改为什么以使 10 显示为 10 而不是 9 感到有点困惑。我想知道是否有人可以提供帮助
最佳答案
你有一个字符串数组,所以当你使用 Min
时和 Max
在此基础上,这些值将作为字符串进行比较。
虽然作为数字 10 > 9
, 作为字符串 "10" < "9"
,因为作为字符串,它们将被排序为 "0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"
.
您可以拆分字符串,然后将每个字符串转换为数字:
int[] numbers =
textBox1.Text.Split(' ')
.Select(s => Int32.Parse(s))
.ToArray();
现在您可以使用 Min
和 Max
在值上,它们将作为数字进行比较。
关于c# - 用户键入时无法显示正确的最大值 (1 2 3 4 5 6 7 8 9 10),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28202891/