【问题标题】:How do I calculate this correctly?我该如何正确计算?
【发布时间】:2019-12-09 14:00:24
【问题描述】:

我有一个 WPF 和 C# 和 SQLITE 系统(这里不重要),它计算人们一天喝的水量。用户有权更改 ML 中的杯子尺寸值和当天的元数据(在这种情况下并不重要)。

事物的计算是:

    takewatervalue = int.Parse(this.takeWater.Text) + takewatervalue;
    counter = takewatervalue * cupml;
    textCounter.Text = counter.ToString();

当人们没有在另一个窗口中更改 cupml 的值(如下所示)时,此计算可以正常工作,当他们更改时,会发生这种情况:

改变cupml值之前的例子:

    cupml = 200 // actual value of cupml choosen for the user

    takewatervalue = int.Parse(this.takeWater.Text)(user input = 1) + takewatervalue(0); // 
    counter = takewatervalue //1 * cupml //200; // = 200 ml -- this is right no problem here
    textCounter.Text = counter.ToString(); // showing to the user the counter and that's good

又一轮:

    cupml = 200 // actual value of cupml choosen for the user
    
    takewatervalue = int.Parse(this.takeWater.Text)(user input = 1) + takewatervalue(1); // 
    counter = takewatervalue //2 * cupml //200; // = 400 ml -- this is right no problem here
    textCounter.Text = counter.ToString(); // showing to the user the counter and that's good

但是当我们更改cupml时,会发生这种情况:

    actual conter value = 400 ML
    cupml = 300 // actual value of cupml choosen for the user in another window
    
    takewatervalue = int.Parse(this.takeWater.Text)(user input = 1) + takewatervalue(2); // 
    counter = takewatervalue //3 * cupml //300; // = 600 ml -- this is not right, the right value is 600 + 400(the old counter) = 1000 ML
    textCounter.Text = counter.ToString(); // showing the wrong counter;

有人知道用另一种方式计算吗?

完整的参考代码在这里有一个 SQLITE 和其他东西的数据库,但这里的重点是这个计算:https://github.com/lucasbarbosagit/BebaAguaAPP

【问题讨论】:

  • 我很困惑。 takewatervalue 是什么? counter 应该算什么?
  • 哦,请不要让我们下载整个项目。发布minimal reproducible example
  • 我会尽量让这更清楚。
  • 我将从重构实际计算开始。原则上它必须类似于newSum = oldSum + (cups * size) 所以让它成为一个函数。为它编写单元测试。如果整个事情仍然不起作用,那么您会知道公式是正确的,但是您输入了错误的内容。
  • 不应该 counter = counter + takewatervalue * cupml?

标签: c# wpf visual-studio sqlite windows-10


【解决方案1】:

在我看来,您计算喝水量的方式存在一些设计问题。 IE。您在不知道实际杯子容量的情况下存储喝过的杯子数量。同时,您可以更改杯子的大小,这实际上就像所有以前喝过的杯子都被更换了一样。

首先,我不会使用 UI 控件的字段作为存储(我会避免使用int.Parse)。

然后,从长远来看,我要么有一个毫升计数器,要么有一个列表 "drink" 事件,每次喝一杯水就会存储一个杯子容量。

因此,想想类似的东西(我还没有编译过):

public class WaterConsumption
{
    private List<int> _DrunkCups = new List<int>();

    public int CupCapacity { get; set; }

    public void DrinkACupOfWater()
    {
        this._DrunkCups.Add(CupCapacity);
    }

    public int GetTotalWaterDrunk()
    {
        return this.DrunkCups.Sum()
    }
}

那么你的表单中上部字段的内容是GetTotalWaterDrunk()的结果,而你的表单下部字段的内容必须存储在CupCapacity中。

让我知道您是否清楚它是否解决了您的问题。

【讨论】:

  • 这可行,但用户在输入中选择的杯子数量在哪里?示例:用户可能会喝 3 杯 200 毫升,而不是 200 毫升的一杯。但这是我的错,没有让这一点更清楚。
  • 如果用户喝了多于一杯水而不是简单地拨打DrinkACupOfWater()更多次。或者为这个方法提供一个重载,它将杯子的数量作为输入,并在内部将足够的杯子添加到列表中。
  • 嗯,我认为这种方法更好,我删除了人们选择喝水量的输入,因为我猜这是一个用户体验缺陷,我在项目中进行了更改。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多