【问题标题】:Running Total C# on btnClick [duplicate]在按钮上运行 Total C# 单击 [重复]
【发布时间】:2018-10-19 14:36:26
【问题描述】:

一切正常,但我需要创建一个运行总计来保存所有捐款。它应该显示截至该点的所有捐赠为慈善机构筹集的总金额(即捐赠的总金额减去所有运营成本)。我知道我需要一个 while 循环或执行 while 循环,以便应用程序运行并不断添加数据。我只是不明白为什么这段代码没有产生运行总数。我正在寻求帮助。有什么我忽略的吗?

private decimal donationBFees = 0;

void deductOperatingCost(ref decimal afterFeesParam)
{
    afterFeesParam = afterFeesParam - (afterFeesParam  / 100 * 17);
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    String donationBeforeFees;
    decimal totalDonationRaised;

    donationBeforeFees = donationBox.Text;
    donationBFees = System.Convert.ToDecimal(donationBeforeFees);


    decimal afterFees = donationBFees;
    deductOperatingCost(ref afterFees);
    afterFeesBox.Text = afterFees.ToString("$###, ##0.00");

    decimal total = 0;

    //This is the for loop I'm using to get the running total
    for (int i = 0; i < afterFees; i++)
    {
        total += afterFees;
        totalDonationRaised = total;
        totalDonationsBox.Text = totalDonationRaised.ToString("$###, ##0.00");
    }
}

【问题讨论】:

  • totalButton_Click() 方法中声明。一旦该方法存在,Total 的值就会丢失。如果您希望total 在多次调用Button_Click() 时保持其值,则该变量需要存在于仅该方法的范围之外
  • 你不能迭代 decimalafterFees... 你需要一个数组或一个集合
  • 你应该只是 updated your last question 而不是再次发布本质上相同的东西
  • 是的,这是真的。我只是觉得描述的信息太多了
  • @Fabjan 是因为变量 total 被覆盖了吗?似乎 for 循环正在锁定系统,因为当我在代码中使用它时,其他部分甚至都不起作用。代码底部的 for 循环会这样做似乎很奇怪。有什么想法吗?

标签: c# for-loop


【解决方案1】:

下面的代码运行正确吗?

private decimal donationBFees = 0;

decimal deductOperatingCost(decimal afterFeesParam)
{
    return afterFeesParam - (afterFeesParam  / 100 * 17);
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    decimal donationBeforeFees = System.Convert.ToDecimal(donationBox.Text);

    decimal afterFees = deductOperatingCost(donationBeforeFees);
    afterFeesBox.Text = afterFees.ToString("$###, ##0.00");

    decimal totalDonationRaised = System.Convert.ToDecimal(totalDonationsBox.Text) + afterFees;
    totalDonationsBox.Text = totalDonationRaised.ToString("$###, ##0.00");
}

【讨论】:

  • 嘿,马特,这不起作用。它对此的抱怨,十进制 afterFees = deductOperatingCost(donationBeforeFees);
  • 你添加deductOperatingCost了吗?错误是什么?
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 2023-02-22
  • 2012-10-16
  • 2015-04-19
  • 2013-04-04
  • 1970-01-01
  • 2018-10-27
  • 2015-01-26
相关资源
最近更新 更多