如何计算文本框值';NumericUpDown的合计

本文关键字:NumericUpDown 何计算 计算 文本 | 更新日期: 2023-09-27 18:19:52

我正在尝试制作一个小的披萨订单,但我的计算有问题。选择披萨后,单价和总计算都可以,但选择添加会带来问题。更改NumericUpDown值后,卡路里是不正确的(所有单位都有固定的价格和卡路里)。NumericUpDown的名称是numberofunit。我如何计算它们?

if (pepper.Checked)
{
    string peppereklendi = 
        Convert.ToString(Convert.ToDouble(unitprice.Text)+ pepperprice);
    unitprice.Text = peppereklendi;
    total.Text = 
        Convert.ToString(Convert.ToDecimal(unitprice.Text) * numberofunit.Value);
    string pepperkaloriekle = 
        Convert.ToString(Convert.ToInt16(gizlikalori.Text) + pepperkalori);
    gizlikalori.Text = pepperkaloriekle;
    amountofcalorie.Text = 
        Convert.ToString(Convert.ToDecimal(gizlikalori.Text) * numberofunit.Value);
}
else
{
    string peppereklendi = unitprice.Text;
    unitprice.Text = 
        Convert.ToString(Convert.ToDouble(peppereklendi) - pepperprice);
    total.Text = Convert.ToString(Convert.ToDecimal(unitprice.Text) * numberofunit.Value);
    string pepperkaloriekle = gizlikalori.Text;
    gizlikalori.Text = 
        Convert.ToString(Convert.ToDouble(pepperkaloriekle) - pepperkalori);
    amountofcalorie.Text = 
        Convert.ToString(Convert.ToDecimal(gizlikalori.Text) * numberofunit.Value);
}

此代码是pepper的复选框代码。

这是我的申请表。

如何计算文本框值';NumericUpDown的合计

您应该真正尝试将计算逻辑与UI逻辑(表单)分离。然后事情会变得更加清楚:

// Get values from the text boxes
decimal up = Convert.ToDecimal(unitprice.Text);
decimal calories = Convert.ToDecimal(gizlikalori.Text);
decimal tot, totCalories;
// Do the calculation
if (pepper.Checked) {
    up = up + pepperprice;
    calories = calories + pepperkalori;
}
tot = up * numberofunit.Value;
totCalories = calories * numberofunit.Value;
// Assign the results to text boxes
unitprice.Text = up.ToString();
total.Text = tot.ToString();
gizlikalori.Text = calories.ToString();
amountofcalorie.Text = totCalories.ToString();

你做错的是,如果没有选择辣椒,你就从单价和单位卡路里中减去辣椒价格和辣椒卡路里。然而,单价(和卡路里)已经没有辣椒了!

我看不出你什么时候进行这个计算,但是,如果你每次增加单位数量都进行计算,那么你每次都会增加辣椒价格!最好为基本单价设置一个单独的变量,在检查添加时保持不变。然后总是从基本单价开始计算。

此外,您正在混合许多不同的数字类型。这毫无意义。

进一步增强代码的下一步是为计算创建一个单独的类。您也可以使用数据绑定。这将完全消除进行转换的需要。请参阅我对以下帖子的回答:在计算中操作文本框变量