0

the number of seconds is shown negative when the stopwatch works for about 15 minutes and on.

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"

This is maybe something about the timer or a logic error, but it looks logic to me. I can't figure out what does not work, please help.

4

4 回答 4

1

这里的问题是 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)

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

于 2013-10-31T14:10:19.930 回答
1

你确定是负数不是秒数吗?你的代码

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
于 2013-10-31T14:10:22.343 回答
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属性已经包含您需要的所有信息,因此您自己重新计算它很愚蠢,而且更容易出错。

于 2013-10-31T14:09:03.353 回答
0

为什么不使用 .ToString 格式?

    Label3.text = timeTook.Elapsed.ToString("hh\:mm\:ss")
于 2013-10-31T14:44:40.133 回答