从组框中求和数值上和

时间:2019-06-13 11:17:26

标签: c#

对于一个项目,我需要从放置在组框中的多个NumericUpDown(要从特定项目订购的项目数量)中获取值。然后,我需要使用这笔款项来获得正确的价格。 一勺冰淇淋= 2,10欧元,两勺冰淇淋= 3,80欧元,三勺冰淇淋= 5,10欧元。

private void btnAdd_Click(object sender, EventArgs e)
{            
    double callories = 0;
    double price = 0;
    string text = "";

    foreach (Control x in grpTypesOfIcecream.Controls)
    {
        int sum1 = 0;

        if (x is NumericUpDown)
        {
            int number = (int)((NumericUpDown)x).Value;                    

            sum1 += number;
            callories += (133 * sum1);

            if (sum1 == 1)
            {
                price += 2.1;
                text += "one scoop of ice";
            }
            else if (sum1 == 2)
            {
                price += 3.8;
                text += "two scoops of ice";
            }
            else if (sum1 == 3)
            {
                price += 5.1;
                text += "three scoops of ice";
            }            
        }
    }
}

每当我启动程序并且一个NumericUpDown的值为2时,我的价格确实是3.8欧元,但是当我使用2个NumericUpDown都具有值1时,它的总和不是我的结果是4.2欧元(2.1 + 2.1)。

每当我拿出2个NumericUpDown,两个值均为1时,它的价格应该是3.8欧元,而不是4.2 ...

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

要解决此问题,只需将int sum1 = 0移到foreach循环之前。将其包含在循环中会使它在foreach循环的每次迭代中都成为该变量的新实例,如果您要保持运行总计,则该变量将不起作用。将其置于循环外部仅声明和初始化一次,因此每次循环时,先前的值仍将存在,供您添加。

private void btnAdd_Click(object sender, EventArgs e)
{

    double callories = 0;
    double price = 0;
    string text = "";
    int sum1 = 0;

    foreach (Control x in grpTypesOfIcecream.Controls)
    {

        if (x is NumericUpDown)
        {
            int number = (int)((NumericUpDown)x).Value;


                sum1 += number;
                callories += (133 * sum1);

                if (sum1 == 1)
                {
                    price += 2.1;
                    text += "one scoop of ice";
                }
                else if (sum1 == 2)
                {
                    price += 3.8;
                    text += "two scoops of ice";
                }
                else if (sum1 == 3)
                {
                    price += 5.1;
                    text += "three scoops of ice";
                }

        }
    }
}