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

标签 c# visual-studio-2013

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();

现在您可以使用 MinMax在值上,它们将作为数字进行比较。

关于c# - 用户键入时无法显示正确的最大值 (1 2 3 4 5 6 7 8 9 10),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28202891/

相关文章:

c# - 如何以编程方式保存 Visual Studio 解决方案?

c# - 如何使我的数字生成器包含最大值? C#

ssl - visual studio无情提示信任IIS Express SSL证书

sql-server - 如何将我的 Microsoft SQL Database_Diagram 存储在 SSDT 项目中?

c# - Resharper 不适用于通用应用程序项目

windows-phone-8 - 单击 "tools"时 Windows Phone 8.1 模拟器 Xde.exe 停止工作

c# - 查询多个数据库的存储库模式

c# - 以存储过程作为参数调用函数

c# - 在 DataFlow 脚本组件中枚举 RecordSet 作为数据源

c - _main() 未解决