首页 > 解决方案 > 如何用 double 和 int 划分两个 TextBox?

问题描述

private void button1_Click(object sender, EventArgs e)
{
    int res = 0;
    try
    {
        res = Convert.ToInt32(costot.Text) / Convert.ToInt32(unidadesp.Text);
        costou.Text = res.ToString();
    }
    catch (Exception ex) { }
}

标签: c#winformstextboxtype-conversion

解决方案


不确定这是否是您所追求的,但它应该为您提供语法。

    private void button1_Click(object sender, EventArgs e)
    {
        int res = 0;
        if (double.TryParse(costot.Text, out double costot) && double.TryParse(unidadesp.Text, out double unidadesp) && unidadesp != 0)
        {
            res = (int)(Math.Round(costot / unidadesp));
            costou.Text = res.ToString();
        }
    }

如果您需要在除法之前将 costot 和 unidadesp 都更改为整数,请执行此操作。

res = (int)(Math.Round(Math.Round(costot) / Math.Round(unidadesp)));

再编辑一次

    private void button1_Click(object sender, EventArgs e)
    {

        if (double.TryParse(textBox1.Text, out double costot) && int.TryParse(textBox2.Text, out int unidadesp) && unidadesp != 0)
        {
           var res = costot / unidadesp;
            textBox3.Text = res.ToString();
        }
    }

推荐阅读