Skip to main content
 首页 » 编程设计

c#之用户键入时无法显示正确的最大值 (1 2 3 4 5 6 7 8 9 10)

2024年08月06日39sharpest

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在值上,它们将作为数字进行比较。