【问题标题】:VB.net calculus from stopwatch return negative minutes秒表中的 VB.net 微积分返回负分钟
【发布时间】:2013-11-11 13:39:57
【问题描述】:

当秒表工作大约 15 分钟及以后,的数量会显示为

Dim timeTook As Stopwatch = Stopwatch.StartNew

'Some time-consuming tasks

timeTook.Stop()

Dim mins As Long = CLng(timeTook.Elapsed.TotalMinutes.ToString) \ 1
Dim secs As Long = CLng(timeTook.Elapsed.TotalSeconds.ToString) \ 1 - 60 * mins
Label3.Text = "Time took: " & mins & " Minutes and " & secs & " Seconds"

这可能与计时器或逻辑错误有关,但对我来说它看起来很合乎逻辑。我无法弄清楚什么不起作用,请帮助。

【问题讨论】:

  • 为什么要将值转换为Long 然后解析它们?为什么不直接使用timeTook.Elapsed.MinutestimeTook.Elapsed.Seconds?如果您转储timeTook.Elapsed.ToString(),这将非常有帮助,并告诉我们您看到了什么值。
  • 你确定是负数不是秒数吗?从您的代码中,我猜您的秒数显示为负数。
  • 是的,对不起。

标签: vb.net time logic stopwatch


【解决方案1】:

如果你这样做的话,它的可读性和效率会更高:

Dim timeTook As Stopwatch = Stopwatch.StartNew
'Some time-consuming tasks
timeTook.Stop()
Label3.Text = "Time took: " & Math.Floor(timeTook.Elapsed.TotalMinutes).ToString() & " Minutes and " & timeTook.Elapsed.Seconds.ToString() & " Seconds"

或者更好:

Label3.Text = "Time took: " & timeTook.Elapsed.ToString()

Elapsed 属性已经包含了你需要的所有信息,所以你自己重新计算它很傻,而且更容易出错。

【讨论】:

  • 我认为timeTook.Elapsed.Seconds 必须是timeTook.Elapsed.Seconds Mod 60。这样它就会显示分钟和剩余秒数。
  • timeTook.Elapsed.Seconds 永远不会超过 59。你正在考虑 timeTook.Elapsed.TotalSeconds
【解决方案2】:

这里的问题是 CLng() 函数四舍五入一个浮点值。因此,如果经过的时间是 0.6 分钟,那么您将得到 mins = 1。您的 secs 值现在将为负数。

您需要截断该值,使其始终向下舍入。让我们也摆脱字符串转换,这没有意义:

Dim mins = Math.Truncate(timeTook.Elapsed.TotalMinutes)
Dim secs = timeTook.Elapsed.TotalSeconds - 60 * mins
Label3.Text = String.Format("Time took: {0:N0} minutes and {1:N0} seconds", _
                            mins, secs)

我会把复数错误留给你来修复:)

【讨论】:

    【解决方案3】:

    您确定负数是分钟数而不是秒数吗?你的代码

    Dim secs As Long = CLng(timeTook.Elapsed.TotalSeconds.ToString) \ 1 - 60 * mins
    

    将始终返回负数,因为any number / negative number is negative

    更好的方法

    Dim secs As Long = timeTook.Elapsed.TotalSeconds mod 60
    

    【讨论】:

      【解决方案4】:

      为什么不使用带有格式的 .ToString?

          Label3.text = timeTook.Elapsed.ToString("hh\:mm\:ss")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多