2

我正在尝试制作一个小的披萨订单,但我的计算有问题。选择披萨后,单价和总计算都可以,但选择添加会带来问题。更改 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);
}

此代码是胡椒的复选框代码。

这是我的申请表格。

4

1 回答 1

6

您真的应该尝试将计算逻辑与 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();

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

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

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

进一步增强代码的下一步是为计算创建一个单独的类。您还可以使用数据绑定。这将完全消除进行转换的需要。请参阅我对以下帖子的回答:manipulating-textbox-variables-in-calculations

于 2012-01-07T21:53:04.907 回答